Wednesday, June 19, 2013

Spring MVC Error handling flow

There are broadly three ways of handling an exception flow using Spring MVC, the objective being to intercept any application exception and present a friendly and informative view back to the user.

1. Using error-page tag in web.xml file:

This is a servlet specs driven approach, where the exceptions that bubble up from the application are intercepted based on either the HTTP response code or the exception type and the handler for the exception is specified using the location sub-tag this way:

If it is a Spring MVC based app, and if the intent is for a Spring MVC view to present the message, then a location should ideally be a Spring controller which can show the content and this can be done for the 2 locations above purely using Spring MVC configuration:

HandlerExceptionResolver(s) are responsible for mapping the exception to views, the simplest approach is to register a SimpleMappingExceptionResolver that can map exception types to view names. The following is a way to register SimpleMappingExceptionResolver using Spring xml bean definition(based on Roo samples):

3. Using @ExceptionHandler

This is my preferred approach and there are two variations to using the @ExceptionHandler annotation.

In the first variation, @ExceptionHandler can be applied to the level of a controller class in which case the exceptions raised by the same controller @RequestMapped methods are handled by the @ExceptionHandler annotated methods.