I am making parallel call using completablefuture like below,
public Response getResponse() {
Response resultClass = new Response();
try {
CompletableFuture<Optional<ClassA>> classAFuture
= CompletableFuture.supplyAsync(() -> service.getClassA() );
CompletableFuture<ClassB> classBFuture
= CompletableFuture.supplyAsync(() -> {
try {
return service.getClassB();
}
catch (Exception e) {
throw new CompletionException(e);
}
});
CompletableFuture<Response> responseFuture =
CompletableFuture.allOf(classAFuture, classBFuture)
.thenApplyAsync(dummy -> {
if (classAFuture.join().isPresent() {
ClassA classA = classAFuture.join();
classA.setClassB(classBFuture.join());
response.setClassA(classA)
}
return response;
});
responseFuture.join();
} catch (CompletionExecution e) {
throw e;
}
return response;
}
I need to add try catch for return service.getClassB()
as it throwing an exception inside the method getClassB
.
Now problem I am facing is if service.getClassB()
throws error it always comes wrapped inside java.util.concurrent.ExecutionException
. There is a scenario where this method throws UserNameNotFoundException but this is wrapped inside ExecutionException
and it is not getting caught in the right place @ControllerAdvice
Exception handler class. I tried different option using throwable but it didn't help.
Is there a good way to handle the exception and unwrap and send it to @ControllerAdvice
class?