I have two completableFutures (cf) in my code. The output of first cf is the input for second cf. But if first cf throws exception, i want to re-throw the same exception and try to not execute the second cf if first one fails.
How can i achieve this?
I found the solution by myself.
vehicleIdCachedLookupService.findVpiByChassisId(chassisId)
.handle((identifier, ex) -> {
if(ex != null){
handleException(ex);
}
return identifier;
})
.thenCompose(identifier -> {
// do something with identifier
}).exceptionally(ex -> {
log.error("Exception .. ", ex);
handleException(ex);
return null;
});
private void handleException(Throwable ex) {
if (ex.getCause() instanceof VPINotFoundException) {
throw new VPINotFoundException(ex.getMessage());
} else {
throw new InternalServerErrorException(ex);
}
}
If you take the above code, if findVpiByChassisId throws exception, it will be handled by handleException method. handleException can re-throw the exception if it doesn't want to execute the next stage thenCompose.
If there is no exception, thenCompose stage will be executed and return the result to the user.
Hope am clear with my question and answer!