Reputation: 1042
I have a set of futures, each of which may throw an exception that I want to log in my way and rethrow, but this doesn't compile:
CompletableFuture<Void> lordOfFutures = CompletableFuture.allOf(future1, future3, future2)
.handle((screen, throwable) -> {
if (throwable!=null) {
LOG.error(throwable, throwable);
throw throwable;
} else {
return screen;
});
Is it possible to log the first exception that occurs and rethrow it?
Upvotes: 0
Views: 780
Reputation: 298233
handle
expects a BiFunction<? super T,Throwable,? extends U>
whose apply
method is not allowed to throw Throwable
. This applies to all functions of the java.util.function
package. But you don’t need to rethrow the throwable at all:
CompletableFuture<Void> lordOfFutures = CompletableFuture.allOf(future1, future3, future2)
.whenComplete((screen, throwable) -> {
if (throwable!=null) {
LOG.error(throwable, throwable);
});
The future returned by whenComplete
will have the same completion state or value as the future you’re calling it on (but only after executing the specified action). So if the future returned by allOf
gets completed exceptionally, the “lordOfFutures
” will be too, and otherwise, it will be completed with the same value (which is always null
here).
Upvotes: 1