@ControllerAdvice and @ExceptionHandler
Handle exceptions globally.
The Problem with Scattered Try/Catch
Handling errors with try/catch in every controller duplicates code and produces inconsistent responses. Spring MVC offers a centralized model: exception handlers that turn exceptions into clean HTTP responses.
Local @ExceptionHandler
A method annotated @ExceptionHandler inside a controller handles the listed exception types for that controller. It maps an exception to a response.
@RestController
public class OrderController {
@ExceptionHandler(OrderNotFoundException.class)
public ResponseEntity<String> handleNotFound(OrderNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
}All lessons in this course
- Bean Validation with @Valid
- Custom Validators
- @ControllerAdvice and @ExceptionHandler
- Problem Details (RFC 7807)