Fallback
Fallbacks allow you to provide an alternative result for a failed execution. They can also be used to suppress exceptions and provide a default result:
Fallback<Object> fallback = Fallback.of(defaultResult);
Throw a custom exception:
Fallback<Object> fallback = Fallback.ofException(e -> new CustomException(e.getException()));
Or compute an alternative result such as from a backup resource:
Fallback<Object> fallback = Fallback.of(this::connectToBackup);
A CompletionStage can be supplied as a fallback:
Fallback<Object> fallback = Fallback.ofStage(this::connectToBackup);
For computations that block, a Fallback can be configured to run asynchronously:
Fallback<Object> fallback = Fallback.builder(this::blockingCall).withAsync().build();
Failure Handling
Fallbacks can be configured to handle only certain results or exceptions:
builder
.handle(ConnectException.class)
.handleResult(null);
When using a Fallback in combination with another policy, it’s common to configure both to handle the same failures.
Event Listeners
Fallbacks support event listeners that can tell you when the last execution attempt failed:
builder.onFailedAttempt(e -> log.error("Connection failed", e.getException()))
When the fallback attempt failed:
builder.onFailure(e -> log.error("Failed to connect to backup", e.getException()));
Or when the execution or fallback attempt succeeded:
builder.onSuccess(e -> log.info("Connection established"));