0
# Exception Handling
1
2
Configurable exception ignoring strategies for handling expected failures during condition evaluation without causing test failures.
3
4
## Capabilities
5
6
### Basic Exception Ignoring
7
8
Control whether exceptions during condition evaluation cause immediate test failure or are treated as false condition results.
9
10
#### Ignore All Exceptions
11
12
```java { .api }
13
/**
14
* Ignore all exceptions during condition evaluation
15
* Exceptions are treated as condition returning false
16
* @return ConditionFactory for further configuration
17
*/
18
ConditionFactory ignoreExceptions();
19
```
20
21
**Usage Example:**
22
```java
23
// Ignore all exceptions until service is ready
24
await().ignoreExceptions()
25
.atMost(30, SECONDS)
26
.until(() -> serviceClient.healthCheck().getStatus() == Status.OK);
27
```
28
29
#### Ignore No Exceptions
30
31
```java { .api }
32
/**
33
* Don't ignore any exceptions (default behavior)
34
* Any exception during condition evaluation fails the test immediately
35
* @return ConditionFactory for further configuration
36
*/
37
ConditionFactory ignoreNoExceptions();
38
```
39
40
### Specific Exception Types
41
42
Ignore only specific exception types while allowing others to fail the test.
43
44
#### Single Exception Type
45
46
```java { .api }
47
/**
48
* Ignore specific exception type during condition evaluation
49
* @param exceptionType class of exceptions to ignore
50
* @return ConditionFactory for further configuration
51
*/
52
ConditionFactory ignoreException(Class<? extends Throwable> exceptionType);
53
54
/**
55
* Alternative method name for ignoring specific exception instances
56
* @param exceptionType class of exceptions to ignore
57
* @return ConditionFactory for further configuration
58
*/
59
ConditionFactory ignoreExceptionsInstanceOf(Class<? extends Throwable> exceptionType);
60
```
61
62
**Usage Examples:**
63
```java
64
// Ignore connection timeouts while waiting for service
65
await().ignoreException(ConnectTimeoutException.class)
66
.atMost(2, MINUTES)
67
.until(() -> httpClient.get("/health").getStatusCode() == 200);
68
69
// Ignore SQL exceptions during database initialization
70
await().ignoreExceptionsInstanceOf(SQLException.class)
71
.until(() -> {
72
try (Connection conn = dataSource.getConnection()) {
73
return conn.isValid(1);
74
}
75
});
76
```
77
78
### Predicate-Based Exception Filtering
79
80
Use predicates to define complex exception ignoring logic.
81
82
#### Predicate Matching
83
84
```java { .api }
85
/**
86
* Ignore exceptions matching the given predicate
87
* @param predicate function that tests whether to ignore exception
88
* @return ConditionFactory for further configuration
89
*/
90
ConditionFactory ignoreExceptionsMatching(Predicate<? super Throwable> predicate);
91
```
92
93
**Usage Examples:**
94
```java
95
// Ignore exceptions with specific message patterns
96
await().ignoreExceptionsMatching(ex ->
97
ex.getMessage() != null && ex.getMessage().contains("Connection refused"))
98
.until(() -> networkService.isConnected());
99
100
// Ignore timeout exceptions but not other network errors
101
await().ignoreExceptionsMatching(ex ->
102
ex instanceof TimeoutException ||
103
(ex instanceof IOException && ex.getMessage().contains("timeout")))
104
.until(() -> remoteService.ping());
105
106
// Ignore exceptions from specific packages
107
await().ignoreExceptionsMatching(ex ->
108
ex.getClass().getPackage().getName().startsWith("com.external.unreliable"))
109
.until(() -> externalApi.getData() != null);
110
```
111
112
### Hamcrest Matcher-Based Filtering
113
114
Use Hamcrest matchers for sophisticated exception matching.
115
116
#### Matcher-Based Filtering
117
118
```java { .api }
119
/**
120
* Ignore exceptions matching the given Hamcrest matcher
121
* @param matcher Hamcrest matcher for exception testing
122
* @return ConditionFactory for further configuration
123
*/
124
ConditionFactory ignoreExceptionsMatching(Matcher<? super Throwable> matcher);
125
```
126
127
**Usage Examples:**
128
```java
129
import static org.hamcrest.Matchers.*;
130
131
// Ignore exceptions that are instances of specific types
132
await().ignoreExceptionsMatching(
133
anyOf(instanceOf(ConnectException.class), instanceOf(SocketTimeoutException.class)))
134
.until(() -> tcpClient.connect());
135
136
// Ignore exceptions with messages containing specific text
137
await().ignoreExceptionsMatching(
138
hasProperty("message", containsString("Service temporarily unavailable")))
139
.until(() -> apiClient.getServiceStatus() == ServiceStatus.AVAILABLE);
140
141
// Complex matcher combining multiple conditions
142
await().ignoreExceptionsMatching(
143
allOf(
144
instanceOf(RuntimeException.class),
145
hasProperty("message", not(containsString("fatal"))),
146
hasProperty("cause", nullValue())
147
))
148
.until(() -> volatileOperation.execute());
149
```
150
151
### Uncaught Exception Handling
152
153
Control handling of uncaught exceptions from other threads.
154
155
#### Enable Uncaught Exception Catching
156
157
```java { .api }
158
/**
159
* Catch uncaught exceptions from other threads
160
* Test will fail if any thread throws uncaught exception
161
* @return ConditionFactory for further configuration
162
*/
163
ConditionFactory catchUncaughtExceptions();
164
```
165
166
#### Disable Uncaught Exception Catching
167
168
```java { .api }
169
/**
170
* Don't catch uncaught exceptions from other threads
171
* Test will not fail due to uncaught exceptions in other threads
172
* @return ConditionFactory for further configuration
173
*/
174
ConditionFactory dontCatchUncaughtExceptions();
175
```
176
177
**Usage Examples:**
178
```java
179
// Fail fast if any background thread has problems
180
await().catchUncaughtExceptions()
181
.until(() -> multiThreadedService.isProcessingComplete());
182
183
// Ignore problems in background threads
184
await().dontCatchUncaughtExceptions()
185
.until(() -> mainOperation.isDone());
186
```
187
188
### Global Exception Configuration
189
190
Set default exception handling behavior for all await statements.
191
192
#### Global Ignore Settings
193
194
```java { .api }
195
/**
196
* Set global default to ignore all exceptions
197
* Affects all subsequent await statements
198
*/
199
static void ignoreExceptionsByDefault();
200
201
/**
202
* Set global default to ignore specific exception type
203
* @param exceptionType exception class to ignore globally
204
*/
205
static void ignoreExceptionByDefault(Class<? extends Throwable> exceptionType);
206
207
/**
208
* Set global default to ignore exceptions matching predicate
209
* @param predicate function to test exceptions globally
210
*/
211
static void ignoreExceptionsByDefaultMatching(Predicate<? super Throwable> predicate);
212
213
/**
214
* Set global default to ignore exceptions matching matcher
215
* @param matcher Hamcrest matcher for global exception testing
216
*/
217
static void ignoreExceptionsByDefaultMatching(Matcher<? super Throwable> matcher);
218
```
219
220
#### Global Uncaught Exception Settings
221
222
```java { .api }
223
/**
224
* Set global default to catch uncaught exceptions
225
* All await statements will catch uncaught exceptions by default
226
*/
227
static void catchUncaughtExceptionsByDefault();
228
229
/**
230
* Set global default to not catch uncaught exceptions
231
* All await statements will ignore uncaught exceptions by default
232
*/
233
static void doNotCatchUncaughtExceptionsByDefault();
234
```
235
236
**Global Configuration Examples:**
237
```java
238
// Set up global exception handling at test class level
239
@BeforeClass
240
public static void configureExceptionHandling() {
241
// Ignore common network exceptions globally
242
ignoreExceptionsByDefaultMatching(ex ->
243
ex instanceof ConnectException ||
244
ex instanceof SocketTimeoutException);
245
246
// Catch uncaught exceptions by default
247
catchUncaughtExceptionsByDefault();
248
}
249
250
@AfterClass
251
public static void resetExceptionHandling() {
252
reset(); // Reset all defaults
253
}
254
```
255
256
### Exception Handling Patterns
257
258
Common patterns for different testing scenarios.
259
260
#### Database Testing
261
262
```java
263
// Ignore database connectivity issues during startup
264
await().ignoreExceptionsMatching(ex ->
265
ex instanceof SQLException ||
266
ex instanceof DataAccessException ||
267
(ex instanceof RuntimeException &&
268
ex.getCause() instanceof SQLException))
269
.atMost(60, SECONDS)
270
.until(() -> {
271
try (Connection conn = dataSource.getConnection()) {
272
return conn.createStatement()
273
.executeQuery("SELECT 1")
274
.next();
275
}
276
});
277
```
278
279
#### Network Service Testing
280
281
```java
282
// Ignore network-related exceptions
283
Predicate<Throwable> isNetworkException = ex ->
284
ex instanceof ConnectException ||
285
ex instanceof SocketTimeoutException ||
286
ex instanceof UnknownHostException ||
287
(ex instanceof IOException &&
288
ex.getMessage().toLowerCase().contains("connection"));
289
290
await().ignoreExceptionsMatching(isNetworkException)
291
.pollInterval(2, SECONDS)
292
.atMost(5, MINUTES)
293
.until(() -> httpClient.get("/api/status").getStatusCode() == 200);
294
```
295
296
#### Message Queue Testing
297
298
```java
299
// Ignore message broker connection issues
300
await().ignoreExceptionsMatching(ex ->
301
ex.getClass().getName().contains("JMSException") ||
302
ex.getClass().getName().contains("AMQException") ||
303
ex.getMessage().contains("broker not available"))
304
.pollInterval(500, MILLISECONDS)
305
.atMost(30, SECONDS)
306
.until(() -> messageProducer.isConnected() && messageConsumer.isConnected());
307
```
308
309
#### Complex Exception Scenarios
310
311
```java
312
// Combine multiple exception handling strategies
313
await().ignoreException(TimeoutException.class) // Ignore timeouts
314
.and().ignoreExceptionsMatching(ex -> // Ignore retryable errors
315
ex instanceof RetryableException ||
316
(ex instanceof RuntimeException &&
317
ex.getMessage().contains("retry")))
318
.and().catchUncaughtExceptions() // But catch uncaught exceptions
319
.atMost(2, MINUTES)
320
.pollInterval(new FibonacciPollInterval(
321
Duration.ofMillis(100),
322
Duration.ofSeconds(5)))
323
.until(() -> complexDistributedOperation.getStatus() == Status.COMPLETED);
324
```