Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExceptionHandler with ResponseBody: set ResponseStatus in method body

I have a method to handle a particular class of exceptions in a Spring MVC environment. The metod (simplified) implementation follows

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

This is works fine, but to return a different ResponseStatus I have to create a new handling 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 changing the return type (maybe serializing the exception class by myself and returning it as a string)?

like image 507
Gabber Avatar asked Sep 02 '13 14:09

Gabber


2 Answers

Add the HttpServletResponse to the method signature and simply 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 that should work.

like image 195
M. Deinum Avatar answered Sep 22 '22 04:09

M. Deinum


Easy done, reading a little more carefully the spring documentation.

It is possible to pass the HttpServletResponse as an object parameter. In such object is possible to set the 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: I deleted this answer yesterday because this solution didn't seem to work. The problem was a bit trickyer: when you manage an exception this way, if the method annotated with ExceptionHandler throws an exception itself then the thrown exception is ignored and the original exception is thrown instead.

My code was somehow like the solution I posted (it threw exception in the start of the method), so I couldn't see the json output, the standard spring exception handler was fired instead. To resolve I simply trycatched the exception-throwing line and everything was ok.

like image 21
Gabber Avatar answered Sep 23 '22 04:09

Gabber