Simple, more carefully read the spring documentation.
You can pass an HttpServletResponse as an object parameter. In such an object, you can set a return code. The syntax is as follows:
@ExceptionHandler(AjaxException.class) @ResponseBody public AjaxException handleException(AjaxException ex,HttpServletResponse response) { //test code ahead, not part of the solution //throw new NullPointerException(); //end of test code response.setStatus(404);//example return ex; }
This will return the json serialization of the exception along with the specified http return code.
EDIT : Yesterday I deleted this answer because this solution does not seem to work. The problem was a little more complicated: when you handle the exception in this way, if the method annotated with the ExceptionHandler throws an exception, then the thrown exception is ignored and the original exception is thrown instead.
My code was kind of like the solution I posted (it threw an exception at the beginning of the method), so I could not see the json output, instead, the standard spring exception handler was launched. To solve, I just tried the exception line and everything was fine.
source share