sargas sargas - 25 days ago 8
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:

@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
  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)
    @ResponseBody
    public ResponseEntity<String> exceptionHandler(Exception e) {
        return new ResponseEntity<>("Something went wrong", HttpStatus.BAD_REQUEST);
    }
}