sargas sargas - 1 year ago 162
Java Question

Spring-boot default exception handler

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

public class RestExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = Exception.class)
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
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?


Answer Source
  1. You don't need to extend ResponseEntityExceptionHandler to make it work.
  2. Setting two HttpStatuses is reaaaaaly bad idea.

@ControllerAdvice(i don't know why i have to put it separetly to have proper formatting)

public class RestExceptionHandler  {
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<String> exceptionHandler(Exception e) {
        return new ResponseEntity<>("Something went wrong", HttpStatus.BAD_REQUEST);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download