I'd like to implement an @ExceptionHandler
that prevents all uncaught exceptions from getting to the client. Something like this...
@ControllerAdvice
public class ExceptionHandlingControllerAdvice {
private static final Logger logger = getLogger(ExceptionHandlingControllerAdvice.class);
@ExceptionHandler(Exception.class)
@ResponseStatus(value = INTERNAL_SERVER_ERROR)
public void handleAnyUncaughtException(Exception e) {
logger.error("This uncaught exception is being blocked from reaching the client.", e);
}
}
But this is getting in the way of the exception handling performed out of the box by DefaultHandlerExceptionResolver
, e.g. to throw 4xx errors on failed @RequestBody
validations checked with @Valid
. It seems like @ExceptionHandler
is taking precedence and returning 500 before the DHER
can try to return a 4xx.
Is there a way to block uncaught exceptions from getting to the client, but still let the DefaultHandlerExceptionResolver
do its job?
I found a solution. I was writing an @ExceptionHandler
that explicitly handles all the standard Spring MVC exceptions, checked the manual for the list, and ran across the ResponseEntityExceptionHandler
base class.
Extending that base class in the @ControllerAdvice
adds an @ExceptionHandler
for the standard exceptions with the crucial difference that you don't have to maintain the list should those exceptions change. The @ControllerAdvice
now looks like this.
@ControllerAdvice
public class ExceptionHandlingControllerAdvice extends ResponseEntityExceptionHandler {
private static final Logger logger = getLogger(ExceptionHandlingControllerAdvice.class);
@ExceptionHandler(Exception.class)
@ResponseStatus(value = INTERNAL_SERVER_ERROR)
public void handleAnyUncaughtException(Exception e) {
logger.error("This uncaught exception is being blocked from reaching the client.", e);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With