Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a generic @ExceptionHandler and DefaultHandlerExceptionResolver play nice?

Tags:

spring-mvc

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?

like image 491
Emerson Farrugia Avatar asked Mar 22 '15 10:03

Emerson Farrugia


1 Answers

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);
    }
}
like image 96
Emerson Farrugia Avatar answered Oct 23 '22 03:10

Emerson Farrugia