Web application errors (404, 500, validation failures, data access errors) can occur in any controller method. Without centralized handling, every method needs try-catch blocks, error view selection, and status code mapping — leading to duplicated error-handling code and inconsistent error responses.
Spring MVC provides a layered exception handling architecture: @ExceptionHandler on controllers handles controller-specific exceptions, @ControllerAdvice provides global exception handling across all controllers, and HandlerExceptionResolver is the lowest-level SPI for complete customization.
- Controller-level:
@ExceptionHandler(SomeException.class)methods in the same controller catch specific exceptions - Global-level:
@ControllerAdviceclasses contain@ExceptionHandlermethods that apply to all controllers - Resolution order: Controller-level → ControllerAdvice → HandlerExceptionResolver chain
- Error views: Exception handler returns ModelAndView with error details and status codes
- REST errors:
@RestControllerAdvicereturns error JSON instead of error views - ResponseEntity: ExceptionHandler methods can return
ResponseEntity<ErrorResponse>for full HTTP response control
- @ExceptionHandler: Method-level annotation for handling specific exception types within a controller
- @ControllerAdvice: Global exception handling across all controllers; also adds model attributes globally
- @RestControllerAdvice: @ControllerAdvice + @ResponseBody, for REST APIs returning JSON error responses
- HandlerExceptionResolver: Interface for custom exception resolution logic; lowest level
- Status codes:
@ResponseStatus(HttpStatus.NOT_FOUND)sets HTTP status on exceptions - ErrorAttributes: Spring Boot provides default error attributes (timestamp, status, error, message, path)
- Built from: Spring MVC — Exception handling is integral to Spring MVC’s request processing
- Built from: Spring Controller — @ExceptionHandler methods live in controllers or @ControllerAdvice
- Related: Spring Form Handling — Validation errors (BindingResult) versus exception handling
- Contrasts with: Try-Catch-Finally — Java try-catch is imperative; Spring MVC exception handling is declarative and cross-cutting
- HandlerExceptionResolver vs @ExceptionHandler: @ExceptionHandler cannot control response status for unhandled exceptions; HandlerExceptionResolver can
- Async exceptions: Exceptions in @Async methods or DeferredResult need separate handling (AsyncExceptionHandler)
- ResponseStatusException: Spring 5+ provides
ResponseStatusExceptionfor programmatic status + reason without custom exception classes - Security exceptions: Spring Security exceptions are handled by the Security filter chain, not ControllerAdvice