AJAX Friendly SimpleMappingExceptionResolver

  • Post author:
  • Post category:Java

If you have a Spring MVC application, you are probably using SimpleMappingExceptionResolver. Here’s the snippet of code in Spring servlet.xml.

	<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<property name="exceptionMappings">
			<props>
				<prop key="java.lang.Exception">error</prop>
			</props>
		</property>
	</bean>

In one of our applications, we needed the usual error page, and an AJAX friendly error page. When we make an AJAX request, we return only the HTML content, with no header or footer. We want the same for our error page, to only return the error content when the request is via AJAX. So here’s how we did it.

First, we changed our error view to redirect to an Error controller.

			<prop key="java.lang.Exception">redirect:/error</prop>

Next, we created an Error controller.

@Controller
public class ErrorController {
	@RequestMapping(value = "/error", method = RequestMethod.GET)
	public String error(HttpServletRequest request) {
		String view = null;
		if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
			view = "error-content;
		} else {
			view = "error";
		}

		return view;
	}
}

Here we checked if the request was via AJAX, by checking the request header “X-Requested-With” for “XMLHttpRequest”. If we know this is an AJAX request, we return only the error content HTML, not the full error page. If it makes sense for your application, you can also include error-content in the error view to minimize duplicate content.

Your Spring error handling should now work for both regular requests and AJAX requests. If you have a better way of implementing this, please let us know in the comments section.