Exception Handling in Spring MVC
Spring MVC provides several complimentary approaches to exception handling but, when teaching Spring MVC, I often find that my students are confused or not comfortable with them.
Today I'm going to show you the various options available. Our goal is to not handle exceptions explicitly in Controller methods where possible. They are a cross-cutting concern better handled separately in dedicated code.
There are three options: per exception, per controller or globally.
Content Negotiation using Views
In my previous post I introduced the concept of content negotiation and the three strategies Spring MVC uses to determine the content requested. In this post I want to extend the concept to supporting multiple views for different content-types using the
ContentNegotiatingViewResolver (or CNVR).
Since we already know how to setup content-negotiation from the previous post, using it to select between multiple views is very straightforward. Simply define a CNVR like this:
<!-- View resolver that delegates to other view resolvers based on the content type --> <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <!-- All configuration is now done by the manager - since Spring V3.2 --> <property name="contentNegotiationManager" ref="cnManager"/> </bean> <!-- Setup a simple strategy: 1. Only path extension is taken into account, Accept headers are ignored. 2. Return HTML by default when not sure. --> <bean id="cnManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"> <property name="ignoreAcceptHeader" value="true"/> <property name="defaultContentType" value="text/html" /> </bean>
Content Negotiation using Spring MVC
There are two ways to generate output using Spring MVC:
- You can use the RESTful
@ResponseBodyapproach and HTTP message converters, typically to return data-formats like JSON or XML. Programmatic clients, mobile apps and AJAX enabled browsers are the usual clients.
- Alternatively you may use view resolution. Although views are perfectly capable of generating JSON and XML if you wish (more on that in my next post), views are normally used to generate presentation formats like HTML for a traditional web-application.
- Actually there is a third possibility - some applications require both, and Spring MVC supports such combinations easily. We will come back to that right at the end.