Card 03/ 07
All 7 cards
ExampleDifficulty: Intermediate1 min
One Handler, Every Controller
An @ExceptionHandler inside one controller only catches exceptions thrown by that controller. @RestControllerAdvice moves the same handler outside every controller, so it catches the exception no matter which one threw it.
@RestControllerAdvice
class GlobalExceptionHandler {
@ExceptionHandler(RideNotFoundException.class)
ResponseEntity<String> handleNotFound(RideNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("centralized: " + ex.getMessage());
}
}GET /rides/1 -> 404 centralized: Ride not found with id: 1
GET /drivers/2 -> 404 centralized: Driver not found with id: 2RideLookupController and DriverLookupController share nothing except throwing RideNotFoundException — and one @RestControllerAdvice class is enough to answer both consistently, with the handler written exactly once.