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
In Spring MVC, exception handling can be managed in various ways. Here's a brief overview followed by a detailed guide:
@ExceptionHandler
: Handle exceptions that are local to a specific controller.ControllerAdvice
: A global error handling mechanism that spans across all controllers.HandlerExceptionResolver
: More advanced mechanism, providing more control over the handling process.@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.
@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.
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.
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>
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.
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; } }
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; } }
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; } }
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; } }
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; } }
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 } }
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 } }
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); } } }
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>