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.