@ExceptionHandler for type Exception not called for Spring exception in custom ResponseEntityExceptionHandler

After reading some blog posts about making a custom exception handler for Spring, I wrote the following class:

@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<Object> exceptionHandler(Exception e) {
        HashMap<String, Object> msg = new HashMap<>(2);
        msg.put("error", HttpStatus.PRECONDITION_FAILED.value());
        msg.put("message", "Something went wrong");
        return new ResponseEntity<>(msg, HttpStatus.BAD_REQUEST);
    }
}

The intent is to send msg in the JSON response instead of giving away the Spring exception what was thrown for whatever reason.

This class isn’t working, however.

When I hit, say, and invalid endpoint for my server API, I get the default response payload:

{
  "timestamp": 1449238700342,
  "status": 405,
  "error": "Method Not Allowed",
  "exception": "org.springframework.web.HttpRequestMethodNotSupportedException",
  "message": "Request method 'POST' not supported",
  "path": "/bad_enpoint"
}

What am I missing?

Thanks.

Answer

Your handler will not be called because you want to map Exception to your custom error response but Spring MVC most likely already has one exception handler registered for Exception class. It also has one that handles HttpRequestMethodNotSupportedException for sure.

It is not a great idea however, to overwrite entire Spring MVC exception handling/mapping anyway. You should only care about specific exceptions – ones that you define.

Please read this article for a bit more insight into Spring MVC exception handling.

Leave a Reply

Your email address will not be published. Required fields are marked *