How do I tell if a Completeable Future failed with an error? I am trying to look through Java Future Library below and find out? Not sure which one to pick.
Right now, when one succeeds, and one fails, trying to find which API had the error.
CompletableFuture<ProductResponse> productFuture = CompletableFuture.supplyAsync(() ->
productAPI(productRequest)
);
CompletableFuture<VendorResponse> vendorFuture= CompletableFuture.supplyAsync(() ->
vendorAPI.postLogin(vendorRequest)
);
try {
CompletableFuture.allOf(productFuture , vendorFuture).join();
} catch (Exception e) {
}
You can check if a specific future failed by checking isCompletedExceptionally()
after it's done:
if (productFuture.isCompletedExceptionally()) {
System.out.println("product request failed!");
}
Or by catching the ExecutionException
via get()
:
try {
productFuture.get();
} catch (ExecutionException e) {
System.out.println("product request failed!");
}
Or you can set a failure callback via exceptionally()
or whenComplete()
:
productFuture = productFuture.whenComplete(
(res, exc) -> System.out.println("product request failed!"));