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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With