Error handling and HTTP status codes with Spring MVC
The best way of handling errors in Spring MVC is implementing HandlerExceptionResolver interface or using the annotation @ExceptionHandler.
Here you have an example using DefaultHandlerExceptionResolver, the default implementation of HandlerExceptionResolver.
public class MyExceptionResolver extends DefaultHandlerExceptionResolver {
@Override
protected ModelAndView doResolveException(HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex) {
try {
if (ex instanceof PossibleSpamException) {
return handlePossibleSpamException((PossibleSpamException) ex, request, response);
}
}
catch (Exception handlerException) {
logger.warn("Handling of [" + ex.getClass().getName() + "] resulted in Exception", handlerException);
}
return super.doResolveException(request, response, handler, ex);
}
private ModelAndView handlePossibleSpamException(PossibleSpamException ex,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); // HTTP Status code 503
return new ModelAndView();
}
}
This resolver is defined in the applicationContext.xml:
<bean id="exceptionResolver" class="domain.MyExceptionResolver" />
And the corresponding JSP is declared in web.xml:
<error-page> <error-code>503</error-code> <location>/WEB-INF/views/errors/503.jsp</location> </error-page>
Advertisement