javaspringrestexceptioncontroller-advice

Custom @ControllerAdvice in Spring for exception handling


I am trying to map exceptions from my rest controllers to responses which have a body, and to do it in a central place.

I have tried this:

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class RestErrorResponseExceptionHandler extends ResponseEntityExceptionHandler {
    @Override
    protected ResponseEntity<Object> handleExceptionInternal(
        Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
        super.handleExceptionInternal(ex, body, headers, status, request);

        return ResponseEntity.status(status).body(Error.from(status));
    }
} 

The problem is that the handler is never triggered.

If I define a custom method with @ExceptionHandler in my rest controllers, or extend something that has @ExceptionHandler, then all works well, but that introduces some bad design.

It is my understanding that Spring will first try to look in controller for exception handling methods, then it will check for registered handlers.

I am trying to verify the behaviour via WebMvcTest, and responses I'm getting are not the Error objects that I'm expecting.

Is there something I'm missing?


Solution

  • The ControllerAdvice is a configuration that have to be registered by Spring. You have to move your class in the config package or you can register it by annotation.

    In my case, I work with a controllerAdvice like this one :

    @ControllerAdvice
    public class GlobalControllerExceptionHandler {
    
        @ExceptionHandler(MyException.class) 
        public ResponseEntity<String> reponseMyException(Exception e) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body("my message");
        }
    }