I am running web services using spring boot. The below snippet is from controller. I have a custom exception class(which extends RuntimeException). To handle exceptions, I have a controller advice as well.
When someMethod() throws a custom exception, I expect to get a 400 - Bad Request. But, completable future bounds the exception and I always receive 500 - Internal Server Error.
CompletableFuture.supplyAsync(() -> {
return someMethod();
}
).whenCompleteAsync((response, throwable) -> {
});
ControllerAdvice
@ControllerAdvice
public class CustomExceptionHandler extends Throwable {
@Order(Ordered.HIGHEST_PRECEDENCE)
@ExceptionHandler(value = CustomException.class)
public ResponseEntity<ErrorResponse> handleCustomException(
CustomException ex) {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setCode("400");
errorResponse.setDescription(ex.getMessage());
return new ResponseEntity<>(errorResponse, new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(value = Exception.class)
public ResponseEntity<ErrorResponse> handleGenericExceptions(Exception exception) {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setCode("500");
errorResponse.setDescription(exception.getMessage());
return new ResponseEntity<>(errorResponse, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
If I throw the custom exception outside of completable future, I get the expected 400 - Bad Request. In the other hand, If I don't have a handler for global exception, I get 400 Bad Request even it is thrown inside of completable future. But, both are not acceptable. I had done this to find the root cause.
How to deal this scenario?