I tried to implement a @ControllerAdvice to globally handle some general exceptions related to my web application. I wanted to send a wrapped JSON response with response status set accordingly. Here is a code sample.
@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 a POJO used to wrap the response. The problem is, despite the @ResponseStatus annotation, the response always has status code 500 (Internal Server Error) with the default error page showing the stack trace. Even the @ResponseBody seems not to work. But the documentation states that I could send a JSON response on an @ExceptionHandler method. I don't understand what I'm doing wrong in here.
I'm using Spring 3.2.8 release framework and Gson is used for message conversion, if that matters.
Any help would be gladly appreciated.
Found the issue. It was because all the getters and setters of the Response POJO were not defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With