Wednesday, February 3, 2021

Spring MVC Exception Handling Tutorial

Exception handling is an important part of any application and Spring MVC applications are no exception. Spring MVC exception handling set up is important so that the user doesn’t suddenly see an exception trace from the server side. By using Spring MVC exception handling you can configure error pages that are displayed with the proper information to the user in case any exception occurs.

This post gives an overview of Spring MVC exception handling, for an example of Spring MVC exception handling refer this post- Spring MVC Exception Handling Example Using @ExceptionHandler And @ControllerAdvice


HandlerExceptionResolver in Spring MVC exception handling

HandlerExceptionResolver is an interface in Spring framework which is to be implemented by objects that can resolve exceptions thrown during handler mapping or execution.

Spring framework delegates the exception handling to a chain of HandlerExceptionResolver beans where you can try to resolve the exception, prepare an error response (HTML error page, error status).

HandlerExceptionResolver implementations in Spring

The available HandlerExceptionResolver implementations in Spring framework are as follows.

HandlerExceptionResolver Description
SimpleMappingExceptionResolver You can configure this resolver or extend it and configure your implementation as a bean. This resolver provides a mapping between exception class names and error view names. Using it you can render error pages in a browser application.
DefaultHandlerExceptionResolver Resolves exceptions raised by Spring MVC and maps them to HTTP status codes.
ResponseStatusExceptionResolver Resolves exceptions with the @ResponseStatus annotation and maps them to HTTP status codes based on the value provided in the @ResponseStatus annotation.
ExceptionHandlerExceptionResolver Resolves exceptions by invoking an @ExceptionHandler method in an @Controller or an @ControllerAdvice class.

Spring MVC exception handling configuration

In your Spring MVC application you can chain exception resolvers by declaring more than one exception resolver beans. You can also set the order property to specify ordering. Higher the order property, the later the exception resolver is positioned in the chain.

If you are using <mvc:annotation-driven> in your XML configuration or @EnableWebMvc in your Java config then Spring framework automatically declares built-in resolvers for default Spring MVC exceptions, for @ResponseStatus annotated exceptions, and for support of @ExceptionHandler methods.

Here is a sample configuration for SimpleMappingExceptionResolver, if MyException a custom exception, is thrown then the view name returned is error, default error view is defaulterror.

<bean class = "org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
  <property name="exceptionMappings">
    <props>
      <prop key="org.netjs.MyException">error</prop>
    </props>
  </property>
  <property name="defaultErrorView" value="defaulterror"/>
</bean>

Return value of HandlerExceptionResolver implementations

As per the contract of HandlerExceptionResolver it can return-

  1. ModelAndView that points to an error view.
  2. Empty ModelAndView if the exception was handled within the resolver.
  3. null if the exception remains unresolved and for subsequent resolvers to try. if the exception remains unresolved by any resolver, it is re-thrown and left to propagate to the Servlet container.

Specifying exception handler in controller class

You can specify exception handling methods with in your controller class by annotating those methods with @ExceptionHandler annotation. The exceptions these exception handler methods are supposed to handle are provided as value with the @ExceptionHandler. For example if you want to set up exception handling method in your controller class for handling exception of type MyException.

@ExceptionHandler(MyException.class)
public ModelAndView handleUserException(HttpServletRequest request, Exception ex){
 ModelAndView mv = new ModelAndView();
 mv.addObject("exception", ex);
 mv.setViewName("error");
 return mv;
}

Specifying global exception handlers using @ControllerAdvice

Though you can add exception handling methods in controller classes for few specific exception but handling the same type of exceptions in different controllers will result in a lot of redundancy. Spring framework provides @ControllerAdvice annotation using which you can set up a class with exception handler methods that are used as global exception handlers i.e. not tied with any controllers and used across controllers.

@ControllerAdvice
public class ExceptionHandler {
 @ExceptionHandler(IOException.class)
 public String IOExceptionHandler() {
  return "error";
 }
}

Servlet container error page

If an exception is not resolved by any HandlerExceptionResolver or if the response status is set to an error status (i.e. 4xx, 5xx), Servlet containers may render a default error page in HTML. For that you can declare an error page mapping in web.xml as follows.

<error-page>
  <location>/error</location>
</error-page>

This can then be mapped to a method in controller class.

@Controller
public class ErrorController {
 @RequestMapping(path = "/error")
 public String handle(HttpServletRequest request) {
  return "defaulterror";
 }
}

That's all for this topic Spring MVC Exception Handling Tutorial. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring MVC Form Example With Bean Validation
  2. Spring MVC Example With @PathVaribale - Creating Dynamic URL
  3. Difference Between @Controller And @RestController Annotations in Spring
  4. Spring MVC Excel Generation Example
  5. Transaction Management in Spring

You may also like-

  1. BeanFactoryPostProcessor in Spring Framework
  2. Spring depends-on Attribute
  3. Excluding Bean From Autowiring in Spring
  4. ServiceLocatorFactoryBean in Spring
  5. Serialization and Deserialization in Java
  6. Java ReentrantLock With Examples
  7. Java Program to Get All The Tables in a DB Schema
  8. Difference Between equals() Method And equality Operator == in Java

No comments:

Post a Comment