ExceptionHandler with ResponseBody: set ResponseStatus to the method body

I have a method for handling a specific exception class in a Spring MVC environment. The methodical (simplified) implementation follows

@ExceptionHandler(AjaxException.class) @ResponseStatus(value=HttpStatus.BAD_REQUEST) @ResponseBody public Exception handleException(AjaxException ex) { return ex; } 

This works fine, but to return another ResponseStatus I need to create a new processing method.

Is it possible to change the response status inside the method body instead of using the @ResponseStatus annotation without changing the return type?

If not, is it possible to achieve the same result by changing the type of the return value (maybe serializing the exception class by itself and returning it as a string)?

+6
source share
2 answers

Add the HttpServletResponse to the method signature and just call the setStatus method.

 @ExceptionHandler(AjaxException.class) @ResponseBody public Exception handleException(AjaxException ex, HttpServletResponse response) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return ex; } 

Something like this should work.

+4
source

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.

+2
source

Source: https://habr.com/ru/post/952989/


All Articles