Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC Interceptor error response not caught by Tomcat custom error handler

In my Spring MVC app (servlet 3.0), I have defined a custom error handler in web.xml:

<error-page>
    <location>/error</location>
</error-page>

which maps to a Controller:

@Controller
class CustomErrorController {

 @RequestMapping("error")
 public String customError(HttpServletRequest request, HttpServletResponse response, Model model) {
...
 }
}

This works fine for most errors, such as 404 errors. However, I have also defined an Interceptor which returns a 403 response if there is no authenticated user:

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    HttpSession httpSession = request.getSession();
    ((HttpServletResponse) response).setStatus(HttpURLConnection.HTTP_FORBIDDEN);
    return false;
}

The 403 response is not being caught by the custom error handler - the browser just gets no response with an error code of 403.

I presume this is because I am doing something incorrectly in the Interceptor - How should I change the code in the Interceptor so that normal error handling works?

like image 780
Black Avatar asked Dec 15 '22 01:12

Black


1 Answers

Change response.setStatus to response.sendError

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    response.sendError(HttpServletResponse.SC_FORBIDDEN);
    return false;
}

This actually issues an error (rather than just stating it) - and forces Tomcat to use the error location as defined in the web.xml

As stated in the HttpServletResponse#setStatus(int) javadoc

If this method [setStatus] is used to set an error code, then the container's error page mechanism will not be triggered. If there is an error and the caller wishes to invoke an error page defined in the web application, then sendError(int, java.lang.String) must be used instead.

like image 75
Will Keeling Avatar answered Mar 01 '23 22:03

Will Keeling