@ResponseStatus and @ResponseBody doesn't work with @ExceptionHandler
I tried to implement @ControllerAdvice
to globally handle some generic exceptions related to my web application. I would like to send a wrapped JSON response with the appropriate response status. Here's some sample code.
@ControllerAdvice
public class GlobalErrorHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(Exception.class)
@ResponseBody
public Response handleAllErrors() {
Response wrapped = new Response(HttpServletResponse.SC_BAD_REQUEST, "error");
wrapped.setMessage("Could not retrieve data");
return wrapped;
}
}
Response
is the POJO used to wrap the response. The problem is that, despite the annotation @ResponseStatus
, the response always has a 500 (Internal Server Error) status code with a default error page displaying the stack trace. Even @ResponseBody
doesn't seem to work. But the documentation states that I can send a JSON response to the method @ExceptionHandler
. I don't understand what I am doing wrong here.
I am using Spring 3.2.8 framework and Gson is used to transform messages if it matters.
Any help would be greatly appreciated.
source to share