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.

A demonstration application that shows the points discussed here can be found at
http://github.com/paulc4/mvc-exceptions. See Sample Application below for details.

NOTE: The demo applications has been revamped and updated (October 2014) to use Spring Boot 1.1.8 and is (hopefully) easier to use and understand.

Using HTTP Status Codes

Normally any unhandled exception thrown when processing a web-request causes the server to return an HTTP 500 response. However, any exception that you write yourself can be annotated with the @ResponseStatus annotation (which supports all the HTTP status codes defined by the HTTP specification). When an annotated exception is thrown from a controller method, and not handled elsewhere, it will automatically cause the appropriate HTTP response to be returned with the specified status-code.

For example, here is an exception for a missing order.

 @ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No such Order")  // 404
 public class OrderNotFoundException extends RuntimeException {
     // ...
 }

And here is a controller method using it:

 @RequestMapping(value="/orders/{id}", method=GET)
 public String showOrder(@PathVariable("id") long id, Model model) {
     Order order = orderRepository.findOrderById(id);

     if (order == null) throw new OrderNotFoundException(id);

     model.addAttribute(order);
     return "orderDetail";
 }

A familiar HTTP 404 response will be returned if the URL handled by this method includes an unknown order id.

Controller Based Exception Handling

Using @ExceptionHandler

You can add extra (@ExceptionHandler) methods to any controller to specifically handle exceptions thrown by request handling (@RequestMapping) methods in the same controller. Such methods can:

  1. Handle exceptions without the @ResponseStatus annotation (typically predefined exceptions that you didn’t write)
  2. Redirect the user to a dedicated error view
  3. Build a totally custom error response

The following controller demonstrates these three options:

@Controller
public class ExceptionHandlingController {

  // @RequestHandler methods
  ...
  
  // Exception handling methods
  
  // Convert a predefined exception to an HTTP Status code
  @ResponseStatus(value=HttpStatus.CONFLICT,
                  reason="Data integrity violation")  // 409
  @ExceptionHandler(DataIntegrityViolationException.class)
  public void conflict() {
    // Nothing to do
  }
  
  // Specify name of a specific view that will be used to display the error:
  @ExceptionHandler({SQLException.class,DataAccessException.class})
  public String databaseError() {
    // Nothing to do.  Returns the logical view name of an error page, passed
    // to the view-resolver(s) in usual way.
    // Note that the exception is NOT available to this view (it is not added
    // to the model) but see "Extending ExceptionHandlerExceptionResolver"
    // below.
    return "databaseError";
  }

  // Total control - setup a model and return the view name yourself. Or
  // consider subclassing ExceptionHandlerExceptionResolver (see below).
  @ExceptionHandler(Exception.class)
  public ModelAndView handleError(HttpServletRequest req, Exception ex) {
    logger.error("Request: " + req.getRequestURL() + " raised " + ex);

    ModelAndView mav = new ModelAndView();
    mav.addObject("exception", ex);
    mav.addObject("url", req.getRequestURL());
    mav.setViewName("error");
    return mav;
  }
}

In any of these methods you might choose to do additional processing - the most common example is to log the exception.

Handler methods have flexible signatures so you can pass in obvious servlet-related objects such as HttpServletRequestHttpServletResponseHttpSession and/or Principle.

Important Note: The Model may not be a parameter of any @ExceptionHandler method. Instead, setup a model inside the method using a ModelAndView as shown by handleError()above.

Exceptions and Views

Be careful when adding exceptions to the model. Your users do not want to see web-pages containing Java exception details and stack-traces. However, it can be useful to put exception details in the page source as a comment, to assist your support people. If using JSP, you could do something like this to output the exception and the corresponding stack-trace (using a hidden <div> is another option).

  <h1>Error Page</h1>
  <p>Application has encountered an error. Please contact support on ...</p>
    
  <!--
    Failed URL: ${url}
    Exception:  ${exception.message}
        <c:forEach items="${exception.stackTrace}" var="ste">    ${ste} 
    </c:forEach>
  -->

For the Thymeleaf equivalent see support.html in the demo application. The result looks like this.

Example of an error page with a hidden exception for support

Global Exception Handling

Using @ControllerAdvice Classes

A controller advice allows you to use exactly the same exception handling techniques but apply them across the whole application, not just to an individual controller. You can think of them as an annotation driven interceptor.

Any class annotated with @ControllerAdvice becomes a controller-advice and three types of method are supported:

  • Exception handling methods annotated with @ExceptionHandler.
  • Model enhancement methods (for adding additional data to the model) annotated with
    @ModelAttribute. Note that these attributes are not available to the exception handling views.
  • Binder initialization methods (used for configuring form-handling) annotated with
    @InitBinder.

We are only going to look at exception handling - see the online manual for more on
@ControllerAdvice methods.

Any of the exception handlers you saw above can be defined on a controller-advice class - but now they apply to exceptions thrown from any controller. Here is a simple example:

@ControllerAdvice
class GlobalControllerExceptionHandler {
    @ResponseStatus(HttpStatus.CONFLICT)  // 409
    @ExceptionHandler(DataIntegrityViolationException.class)
    public void handleConflict() {
        // Nothing to do
    }
}

If you want to have a default handler for any exception, there is a slight wrinkle. You need to ensure annotated exceptions are handled by the framework. The code looks like this:

@ControllerAdvice
class GlobalDefaultExceptionHandler {
  public static final String DEFAULT_ERROR_VIEW = "error";

  @ExceptionHandler(value = Exception.class)
  public ModelAndView
  defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
    // If the exception is annotated with @ResponseStatus rethrow it and let
    // the framework handle it - like the OrderNotFoundException example
    // at the start of this post.
    // AnnotationUtils is a Spring Framework utility class.
    if (AnnotationUtils.findAnnotation
                (e.getClass(), ResponseStatus.class) != null)
      throw e;

    // Otherwise setup and send the user to a default error-view.
    ModelAndView mav = new ModelAndView();
    mav.addObject("exception", e);
    mav.addObject("url", req.getRequestURL());
    mav.setViewName(DEFAULT_ERROR_VIEW);
    return mav;
  }
}

Going Deeper

HandlerExceptionResolver

Any Spring bean declared in the DispatcherServlet’s application context that implementsHandlerExceptionResolver will be used to intercept and process any exception raised in the MVC system and not handled by a Controller. The interface looks like this:

public interface HandlerExceptionResolver {
    ModelAndView resolveException(HttpServletRequest request, 
            HttpServletResponse response, Object handler, Exception ex);
}

The handler refers to the controller that generated the exception (remember that@Controller instances are only one type of handler supported by Spring MVC. For example:HttpInvokerExporter and the WebFlow Executor are also types of handler).

Behind the scenes, MVC creates three such resolvers by default. It is these resolvers that implement the behaviours discussed above:

  • ExceptionHandlerExceptionResolver matches uncaught exceptions against for suitable@ExceptionHandler methods on both the handler (controller) and on any controller-advices.
  • ResponseStatusExceptionResolver looks for uncaught exceptions annotated by@ResponseStatus (as described in Section 1)
  • DefaultHandlerExceptionResolver converts standard Spring exceptions and converts them
    to HTTP Status Codes (I have not mentioned this above as it is internal to Spring MVC).

These are chained and processed in the order listed (internally Spring creates a dedicated bean - the HandlerExceptionResolverComposite to do this).

Notice that the method signature of resolveException does not include the Model. This is why @ExceptionHandler methods cannot be injected with the model.

You can, if you wish, implement your own HandlerExceptionResolver to setup your own custom exception handling system. Handlers typically implement Spring’s Ordered interface so you can define the order that the handlers run in.

SimpleMappingExceptionResolver

Spring has long provided a simple but convenient implementation ofHandlerExceptionResolver that you may well find being used in your appication already - theSimpleMappingExceptionResolver. It provides options to:

  • Map exception class names to view names - just specify the classname, no package needed.
  • Specify a default (fallback) error page for any exception not handled anywhere else
  • Log a message (this is not enabled by default).
  • Set the name of the exception attribute to add to the Model so it can be used inside a View
    (such as a JSP). By default this attribute is named exception. Set to null to disable. Remember that views returned from @ExceptionHandler methods do not have access to the exception but views defined to SimpleMappingExceptionResolver do.

Here is a typical configuration using XML:

  <bean id="simpleMappingExceptionResolver" class=
     "org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
      <map>
         <entry key="DatabaseException" value="databaseError"/>
         <entry key="InvalidCreditCardException" value="creditCardError"/>
      </map>
    </property>

    <!-- See note below on how this interacts with Spring Boot -->
    <property name="defaultErrorView" value="error"/>
    <property name="exceptionAttribute" value="ex"/>
        
    <!-- Name of logger to use to log exceptions. Unset by default, 
           so logging is disabled unless you set a value. -->
    <property name="warnLogCategory" value="example.MvcLogger"/>
  </bean>

Or using Java Configuration:

@Configuration
@EnableWebMvc  // Optionally setup Spring MVC defaults (if you aren't using
               // Spring Boot & haven't specified @EnableWebMvc elsewhere)
public class MvcConfiguration extends WebMvcConfigurerAdapter {
  @Bean(name="simpleMappingExceptionResolver")
  public SimpleMappingExceptionResolver
                  createSimpleMappingExceptionResolver() {
    SimpleMappingExceptionResolver r =
                new SimpleMappingExceptionResolver();

    Properties mappings = new Properties();
    mappings.setProperty("DatabaseException", "databaseError");
    mappings.setProperty("InvalidCreditCardException", "creditCardError");

    r.setExceptionMappings(mappings);  // None by default
    r.setDefaultErrorView("error");    // No default
    r.setExceptionAttribute("ex");     // Default is "exception"
    r.setWarnLogCategory("example.MvcLogger");     // No default
    return r;
  }
  ...
}

The defaultErrorView property is especially useful as it ensures any uncaught exception generates a suitable application defined error page. (The default for most application servers is to display a Java stack-trace - something your users should never see).

Extending SimpleMappingExceptionResolver

It is quite common to extend SimpleMappingExceptionResolver for several reasons:

  • Use the constructor to set properties directly - for example to enable exception logging and set the logger to use
  • Override the default log message by overriding buildLogMessage. The default implementation always returns this fixed text:
    • Handler execution resulted in exception
  • To make additional information available to the error view by overridingdoResolveException

For example:

public class MyMappingExceptionResolver extends SimpleMappingExceptionResolver {
  public MyMappingExceptionResolver() {
    // Enable logging by providing the name of the logger to use
    setWarnLogCategory(MyMappingExceptionResolver.class.getName());
  }

  @Override
  public String buildLogMessage(Exception e, HttpServletRequest req) {
    return "MVC exception: " + e.getLocalizedMessage();
  }
    
  @Override
  protected ModelAndView doResolveException(HttpServletRequest req,
        HttpServletResponse resp, Object handler, Exception ex) {
    // Call super method to get the ModelAndView
    ModelAndView mav = super.doResolveException(req, resp, handler, ex);
        
    // Make the full URL available to the view - note ModelAndView uses
    // addObject() but Model uses addAttribute(). They work the same. 
    mav.addObject("url", request.getRequestURL());
    return mav;
  }
}

This code is in the demo application as ExampleSimpleMappingExceptionResolver

Extending ExceptionHandlerExceptionResolver

It is also possible to extend ExceptionHandlerExceptionResolver and override its
doResolveHandlerMethodException method in the same way. It has almost the same signature (it just takes the new HandlerMethod instead of a Handler).

To make sure it gets used, also set the inherited order property (for example in the constructor of your new class) to a value less than MAX_INT so it runs before the default ExceptionHandlerExceptionResolver instance (it is easier to create your own handler instance than try to modify/replace the one created by Spring). SeeExampleExceptionHandlerExceptionResolver in the demo app for more.

Errors and REST

RESTful GET requests may also generate exceptions and we have already seen how we can return standard HTTP Error response codes. However, what if you want to return information about the error? This is very easy to do. Firstly define an error class:

public class ErrorInfo {
    public final String url;
    public final String ex;

    public ErrorInfo(String url, Exception ex) {
        this.url = url;
        this.ex = ex.getLocalizedMessage();
    }
}

Now we can return an instance from a handler as the @ResponseBody like this:

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MyBadDataException.class)
@ResponseBody ErrorInfo
handleBadRequest(HttpServletRequest req, Exception ex) {
    return new ErrorInfo(req.getRequestURL(), ex);
} 

What to Use When?

As usual, Spring likes to offer you choice, so what should you do? Here are some rules of thumb. However if you have a preference for XML configuration or Annotations, that’s fine too.

  • For exceptions you write, consider adding @ResponseStatus to them.
  • For all other exceptions implement an @ExceptionHandler method on a@ControllerAdvice class or use an instance of SimpleMappingExceptionResolver. You may well have SimpleMappingExceptionResolver configured for your application already, in which case it may be easier to add new exception classes to it than implement a@ControllerAdvice.
  • For Controller specific exception handling add @ExceptionHandler methods to your controller.
  • Warning: Be careful mixing too many of these options in the same application. If the same exception can be handed in more than one way, you may not get the behavior you wanted.@ExceptionHandler methods on the Controller are always selected before those on any@ControllerAdvice instance. It is undefined what order controller-advices are processed.

Sample Application

A demonstration application can be found at github. It uses Spring Boot and Thymeleaf to build a simple web application.

The application was revised (Oct 2014) and is (hopefully) better and easier to understand. The fundamentals stay the same. It uses Spring Boot V1.1.8 and Spring 4.1 but the code is applicable to Spring 3.x also.

The demo is running on Cloud Foundry at http://mvc-exceptions-v2.cfapps.io/.

About the Demo

The application leads the user through 5 demo pages, highlighting different exception handling techniques:

  1. A controller with @ExceptionHandler methods to handle its own exceptions
  2. A contoller that throws exceptions for a global ControllerAdvice to handle
  3. Using a SimpleMappingExceptionResolver to handle exceptions
  4. Same as demo 3 but with the SimpleMappingExceptionResolver disabled for comparison
  5. Shows how Spring Boot generates its error page

A description of the most important files in the application and how they relate to each demo can be found in the project’s README.md.

The home web-page is index.html which:

  • Links to each demo page
  • Links (bottom of the page) to Spring Boot endpoints for those interested in Spring Boot.

Each demo page contains several links, all of which deliberately raise exceptions. You will need to use the back-button on your browser each time to return to the demo page.

Thanks to Spring Boot, you can run this demo as a Java application (it runs an embedded Tomcat container). To run the application, you can use one of the following (the second is thanks to the Spring Boot maven plugin):

  • mvn exec:java
  • mvn spring-boot:run

Your choice. The home page URL will be http://localhost:8080.

Spring Boot and Error Handling

Spring Boot allows a Spring project to be setup with minimal configuration. Spring Boot creates sensible defaults automatically when it detects certain key classes and packages on the classpath. For example if it sees that you are using a Servlet environment, it sets up Spring MVC with the most commonly used view-resolvers, hander mappings and so forth. If it sees JSP and/or Thymeleaf, it sets up these view-technologies.

Spring MVC offers no default (fall-back) error page out-of-the-box. The most common way to set a default error page has always been the SimpleMappingExceptionResolver (since Spring V1 in fact). However Spring Boot does provide for a fallback error-handling page.

At start-up, Spring Boot tries to find a mapping for /error. By convention, a URL ending in/error maps to a logical view of the same name: error. In the demo application this view maps in turn to the error.html Thymeleaf template. (If using JSP, it would map to error.jspaccording to the setup of your InternalResourceViewResolver).

If no mapping from /error to a View can be found, Spring Boot defines its own fall-back error page - the so-called “Whitelabel Error Page” (a minimal page with just the HTTP status information and any error details, such as the message from an uncaught exception). If you rename the error.html template to, say, error2.html then restart, you will see it being used.

By defining a Java configuration @Bean method called defaultErrorView() you can return your own error View instance. (see Spring Boot’s ErrorMvcAutoConfiguration class for more information).

What if you are already using SimpleMappingExceptionResolver to setup a default
error view? Simple, make sure the defaultErrorView defines the same view that Spring Boot uses: error. Or you can disable Spring boot’s error page by setting the property
server.error.whitelabel.enabled to false (note: this property has been renamed fromerror.whitelabel.enabled since I wrote this blog). Your container’s default error page is used instead.

Spring Boot properties are normally set in application.properties or application.yml. Alternatively, you can set them in code - see Main for an example.

Note that in the demo, the defaultErrorView property of theSimpleMappingExceptionResolver is deliberately set not to error but to defaultErrorPage so you can see when the handler is generating the error page and when Spring Boot is responsible. Normally both would be set to error.

Also in the demo application I show how to create a support-ready error page with a stack-trace hidden in the HTML source (as a comment). Ideally support should get this information from the logs, but life isn’t always ideal. Regardless, what this page does show is how the underlying error-handling method handleError creates its own ModelAndView to provide extra information in the error page. See:

  • ExceptionHandlingController.handleError() on github
  • GlobalControllerExceptionHandler.handleError() on github
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值