Harold L. Brown
Harold L. Brown

Reputation: 9956

Change response code in javax.servlet.http.HttpServlet

In an implementation of javax.servlet.http.HttpServlet an exception is thrown in a method. So the HTTP response code is 500.

Is it somehow possible to set the response code to something else? Or is it every time 500 whenever an exception occurs?

Upvotes: 1

Views: 2489

Answers (1)

BalusC
BalusC

Reputation: 1108842

Just check the precondition or catch the exception and set the desired response status via HttpServletResponse#setStatus() or HttpServletResponse#sendError(), depending on the nature of the status code (4nn/5nn == error).

The way how your question is formulated suggests that it's in your situation not possible to perform a simple preconditional check using e.g. an if statement like below basic example:

if (foo != null) { 
    processFoo(request, response, foo);
}
else {
    response.sendError(HttpServletResponse.SC_BAD_REQUEST);
}

Apparently it's a 3rd party servlet or so. In that case, create a servlet filter which does below job in Filter#doFilter() method and map it to the desired servlet:

try {
    chain.doFilter(request, response);
}
catch (ServletException e) {
    if (e.getRootCause() instanceof IllegalArgumentException) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
    else {
        throw e;
    }
}

Substitute the IllegalArgumentException with the exception of interest, and of course the SC_BAD_REQUEST (400) with the status code of interest.

Either way, this won't consult <error-page><exception-type> anymore and will thus end up in below error page:

<error-page>
    <status-code>400</status-code>
    </location>/WEB-INF/errorpages/400.jsp</location>
</error-page>

Upvotes: 1

Related Questions