My tech blog

Error handling and HTTP status codes with Spring MVC

leave a comment »

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 {

	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:


Written by alexcuesta

May 11, 2011 at 11:09 am

Posted in Java

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: