In Spring MVC, handling exceptions is an essential part of building robust applications. It ensures that errors are managed gracefully and the user experience remains intact, even when something goes wrong. Spring provides several mechanisms to handle exceptions efficiently.
Using @ExceptionHandler
Spring MVC offers the @ExceptionHandler
annotation to handle exceptions at the controller level. This method allows you to specify which exceptions are to be handled by the method.
1 2 3 4 5 6 7 8 9 |
@Controller public class MyController { @ExceptionHandler(Exception.class) public String handleException(Exception e, Model model) { model.addAttribute("error", e.getMessage()); return "error"; } } |
In this example, any exception thrown in the controller is caught and handled by the handleException
method.
Global Exception Handling with @ControllerAdvice
To handle exceptions globally across all controllers, Spring provides @ControllerAdvice
. This is useful when you want a centralized approach to exception handling.
1 2 3 4 5 6 7 8 9 |
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public String handleGlobalException(Exception e, Model model) { model.addAttribute("error", e.getMessage()); return "globalError"; } } |
With @ControllerAdvice
, you can apply exception handling to all controllers without writing redundant code in each controller.
Custom Error Pages
Spring MVC allows you to define custom error pages that will be shown when an error occurs. You can configure them in the web.xml
or application properties.
For example, in application.properties
:
1 |
server.error.path=/error |
Then, create a controller for the error page:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@Controller public class ErrorController implements org.springframework.boot.web.servlet.error.ErrorController { @RequestMapping("/error") public String handleError() { return "customErrorPage"; } @Override public String getErrorPath() { return "/error"; } } |
This method ensures that users are presented with a friendly, custom error page instead of the default error message.
Using ResponseStatusException
Spring also provides ResponseStatusException
for returning specific HTTP status codes when an exception occurs.
1 2 3 4 5 6 |
@ResponseStatus(HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException { public ResourceNotFoundException(String message) { super(message); } } |
We can use this exception in controllers to indicate that a resource was not found:
1 2 3 4 5 6 7 |
@GetMapping("/resource/{id}") public Resource getResource(@PathVariable Long id) { if (id == null) { throw new ResourceNotFoundException("Resource not found"); } return resourceService.getResource(id); } |