简体   繁体   中英

@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.

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.

  1. You don't need to extend ResponseEntityExceptionHandler to make it work.
  2. Setting two HttpStatuses is reaaaaaly bad idea.
    @ControllerAdvice
    public class RestExceptionHandler  {
        @ExceptionHandler(value = Exception.class)
        @ResponseBody
        public ResponseEntity<String> exceptionHandler(Exception e) {
            return new ResponseEntity<>("Something went wrong", HttpStatus.BAD_REQUEST);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM