orvar_mobenga February 2016

Setting the (http)status code (to something other than 500) after an exception in Spring

As the title implies I want to change the http status after an exception occured. The short background is that to be able to show an error page I need to send a status code of 200 to the client. (On error status codes it dumps the data and shows a generic error popup)

To test this I have:

    @RequestMapping(value= "/err")
    public String throwError()
    {
        throw new IllegalStateException();
    }

In web-xml:

    <error-page>
        <error-code>500</error-code>
        <location>/errorPage</location>
    </error-page>

And the errorPage controller (gets called)

    @RequestMapping(value = "/errorPage", method = RequestMethod.GET)
    public String errorPage(HttpServletResponse response, Model model, Locale locale ) {
        int errorStatus = response.getStatus();
        response.reset();
        model.addAttribute("errorStatus", errorStatus);
        response.setStatus(HttpServletResponse.SC_ACCEPTED);
        LOGGER.debug("---------->" + response.getStatus());
        return "errorPage";
    }

The catalina log output is 200 BUT the response in the client is:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Somewhere Spring encodes the exception as a statuscode 500 (I suppose it is in the HandlerExceptionResolver chain?) and then my errorPage controller is called. Spring seems to remember that an exception was thrown and ignores (or recodes?) the status code to 500 after the controller returns.

The confusing (or maybe not?) thing is that if I return a Response Entity from the errorPage controller and set the status code this will be honored. Eg:

    return new ResponseEntity(HttpStatus.ACCEPTED);

I suppose that this is not a bug but a feature and that Spring knows better than me and I s

Answers


Akhil Sudhakaran February 2016

You can set status code by using the following code

@RequestMapping(value= "/err")
public String throwError()
{
     throw new IllegalStateException(message,
                         errorCode);
}

Post Status

Asked in February 2016
Viewed 1,793 times
Voted 12
Answered 1 times

Search




Leave an answer