Spring 3 One Approach to Exception Handling for MVC when using JSON

Whenever an exception (such as a binding exception) came up in my Spring 3 MVC app, Spring would return and HTML page with the stack trace. I don’t want this. Besides not exposing the stack trace, I need well formatted JSON in my response, not an HTML page. I haven’t quite got a grip on exception handling in Spring. I’ve read a ton of entries in stack overflow and I get that @Exception works per controller, but for this case, I wanted to handle the exceptions that occur before you even get to the controller. I finally found one model that is working for me. There are probably other ways to do this and I hope to discover and understand them at some point, but this was actually fairly simple.

Thanks to Google App Engine + JAVA + Spring + REST + Mapping Exceptions to Errors for JSON for providing me with a solution. The entry at Wet Feet is very well written. I’m just copying my version here.

1. Create your own class that implements the HandlerExceptionResolver. I used my own view, but the Wet Feet blog entry uses MappingJacksonJsonView. The WebUtil call in the code is my own code to build the JSON.

package com.ahlearns.mystuff;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

public class JsonExceptionResolver implements HandlerExceptionResolver {
	
	protected final Logger log = LogManager.getLogger(getClass());
	
	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		log.error("Error occurred for handler [" + handler + "]", ex);
		ModelAndView mav = new ModelAndView();
        	mav.setViewName("error");
        	mav.addObject("jsonMsg", WebUtil.getJsonSuccessMsg(false, "An unexpected error occurred."));
        	return mav;
	}
}

2. Add the following bean definition to your spring config. Spring will detect it and route exceptions to the resolver.

<bean id="exceptionResolver" class="com.ahlearns.mystuff.JsonExceptionResolver" />
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s