Spring MVC Tutorial

Core Spring MVC

Spring MVC - Annotation

Spring MVC - Form Handling

Spring MVC with JSTL

Spring MVC with REST API

Spring MVC with Database

Spring MVC - Exception Handling

In Spring MVC, exception handling can be managed in various ways. Here's a brief overview followed by a detailed guide:

  1. @ExceptionHandler: Handle exceptions that are local to a specific controller.
  2. ControllerAdvice: A global error handling mechanism that spans across all controllers.
  3. HandlerExceptionResolver: More advanced mechanism, providing more control over the handling process.

1. Using @ExceptionHandler

In a specific controller, you can handle exceptions using the @ExceptionHandler annotation.

@Controller
public class MyController {

    @RequestMapping("/some-endpoint")
    public String someEndpoint() {
        throw new RuntimeException("Exception from /some-endpoint");
    }

    @ExceptionHandler(RuntimeException.class)
    public ModelAndView handleRuntimeException(RuntimeException ex) {
        ModelAndView mav = new ModelAndView("error");
        mav.addObject("message", ex.getMessage());
        return mav;
    }
}

Here, if a RuntimeException is thrown from any method in MyController, the handleRuntimeException method will be invoked.

2. Using @ControllerAdvice

For a global exception handler that works across all controllers, use the @ControllerAdvice annotation.

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public ModelAndView handleRuntimeException(RuntimeException ex) {
        ModelAndView mav = new ModelAndView("error");
        mav.addObject("message", ex.getMessage());
        return mav;
    }

    @ExceptionHandler(NullPointerException.class)
    public ModelAndView handleNullPointerException(NullPointerException ex) {
        ModelAndView mav = new ModelAndView("nullPointerError");
        mav.addObject("message", "A null value was encountered!");
        return mav;
    }
}

This class will handle exceptions for all controllers in the application.

3. Using HandlerExceptionResolver

For more advanced control, you can implement the HandlerExceptionResolver interface:

@Component
public class CustomHandlerExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView mav = new ModelAndView("error");
        if (ex instanceof NullPointerException) {
            mav.setViewName("nullPointerError");
            mav.addObject("message", "A null value was encountered!");
        } else {
            mav.addObject("message", ex.getMessage());
        }
        return mav;
    }
}

This approach offers more flexibility, like inspecting the handler that caused the exception or modifying the HTTP response directly.

4. Displaying Error Information in Views

In your JSP (e.g., error.jsp), display the error message:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
    <h1>Error</h1>
    <p><c:out value="${message}" /></p>
</body>
</html>

Best Practices:

  • Provide User-Friendly Error Messages: Instead of technical messages, present users with friendly and understandable messages.

  • Log Errors: Ensure that while you handle user-facing errors gracefully, the actual error details are logged on the server side for diagnostics.

  • Error Page Consistency: Ensure that your error pages are consistent with the rest of your application in terms of look and feel.

  • Differentiate Between Error Types: Not all errors are the same. Distinguish between not found errors (404), server errors (500), unauthorized errors (401), etc.

Remember to integrate these strategies based on your application's requirements and the user experience you wish to provide.

  1. Spring MVC Exception Handling Example:

    • Description: This is a basic example demonstrating how to handle exceptions in a Spring MVC application. It covers the setup of a global exception handler to manage unexpected errors.

    • Code Snippet: (Global Exception Handler)

      @ControllerAdvice
      public class GlobalExceptionHandler {
          @ExceptionHandler(Exception.class)
          public ModelAndView handleException(Exception ex) {
              ModelAndView modelAndView = new ModelAndView("error");
              modelAndView.addObject("errorMessage", "An error occurred: " + ex.getMessage());
              return modelAndView;
          }
      }
      
  2. Global Exception Handling in Spring MVC:

    • Description: This example expands on the previous one, emphasizing a global approach to exception handling across the entire Spring MVC application.

    • Code Snippet: (Enhanced Global Exception Handler)

      @ControllerAdvice
      public class GlobalExceptionHandler {
          @ExceptionHandler(Exception.class)
          public ModelAndView handleException(Exception ex) {
              // Logging the exception
              logger.error("An error occurred: " + ex.getMessage());
      
              // Sending a custom error response
              ModelAndView modelAndView = new ModelAndView("error");
              modelAndView.addObject("errorMessage", "An unexpected error occurred. Please try again later.");
              return modelAndView;
          }
      }
      
  3. Handling Exceptions in Spring MVC Controllers:

    • Description: This example focuses on handling exceptions within specific Spring MVC controllers. It shows how to use @ExceptionHandler at the controller level.

    • Code Snippet: (Controller-level Exception Handling)

      @Controller
      @RequestMapping("/items")
      public class ItemController {
          @ExceptionHandler(ItemNotFoundException.class)
          public ModelAndView handleItemNotFoundException(ItemNotFoundException ex) {
              ModelAndView modelAndView = new ModelAndView("itemNotFound");
              modelAndView.addObject("errorMessage", "Item not found: " + ex.getItemId());
              return modelAndView;
          }
      }
      
  4. Custom Exception Handling in Spring MVC:

    • Description: In this example, you create custom exceptions and handle them in a customized way using Spring MVC's exception handling mechanisms.

    • Code Snippet: (Custom Exception and Handler)

      public class CustomException extends RuntimeException {
          // Custom exception properties and methods
      }
      
      @ControllerAdvice
      public class CustomExceptionHandler {
          @ExceptionHandler(CustomException.class)
          public ModelAndView handleCustomException(CustomException ex) {
              ModelAndView modelAndView = new ModelAndView("customError");
              modelAndView.addObject("errorMessage", "Custom error occurred: " + ex.getMessage());
              return modelAndView;
          }
      }
      
  5. ExceptionResolver in Spring MVC:

    • Description: This example explores the use of HandlerExceptionResolver for customizing exception resolution strategy in Spring MVC.

    • Code Snippet: (ExceptionResolver Implementation)

      public class CustomExceptionResolver implements HandlerExceptionResolver {
          @Override
          public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
                                              Object handler, Exception ex) {
              ModelAndView modelAndView = new ModelAndView("customError");
              modelAndView.addObject("errorMessage", "An error occurred: " + ex.getMessage());
              return modelAndView;
          }
      }
      
  6. ControllerAdvice for Exception Handling in Spring MVC:

    • Description: This example leverages @ControllerAdvice to create a global exception handler that can be shared across multiple controllers.

    • Code Snippet: (ControllerAdvice)

      @ControllerAdvice
      public class GlobalExceptionHandler {
          @ExceptionHandler(Exception.class)
          public ModelAndView handleException(Exception ex) {
              // Custom exception handling logic
          }
      }
      
  7. Exception Handling with @ExceptionHandler in Spring MVC:

    • Description: This example illustrates the use of @ExceptionHandler annotation within a controller to handle specific exceptions.

    • Code Snippet: (Controller with @ExceptionHandler)

      @Controller
      @RequestMapping("/users")
      public class UserController {
          @ExceptionHandler(UserNotFoundException.class)
          public ModelAndView handleUserNotFoundException(UserNotFoundException ex) {
              // Custom exception handling logic
          }
      }
      
  8. Logging Exceptions in Spring MVC:

    • Description: This example demonstrates how to log exceptions in a Spring MVC application using a logging framework such as SLF4J or Log4j.

    • Code Snippet: (Logging Exception)

      @Controller
      @RequestMapping("/logs")
      public class LogController {
          private static final Logger logger = LoggerFactory.getLogger(LogController.class);
      
          @GetMapping("/trigger")
          public void triggerException() {
              try {
                  // Code that may throw an exception
              } catch (Exception ex) {
                  logger.error("An error occurred: " + ex.getMessage(), ex);
              }
          }
      }
      
  9. Error Pages and Exception Handling in Spring MVC:

    • Description: This example explores how to configure custom error pages for different HTTP status codes and exceptions in a Spring MVC application.

    • Code Snippet: (Web.xml Configuration)

      <error-page>
          <error-code>404</error-code>
          <location>/error/404</location>
      </error-page>
      
      <error-page>
          <exception-type>java.lang.Exception</exception-type>
          <location>/error/generic</location>
      </error-page>