Card 03/ 07

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.

java
@RestControllerAdvice
class GlobalExceptionHandler {
    @ExceptionHandler(RideNotFoundException.class)
    ResponseEntity<String> handleNotFound(RideNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("centralized: " + ex.getMessage());
    }
}
text
GET /rides/1   -> 404 centralized: Ride not found with id: 1
GET /drivers/2 -> 404 centralized: Driver not found with id: 2
run in a container — two separate controllers, one handler, both throwing the same RideNotFoundException

RideLookupController and DriverLookupController share nothing except throwing RideNotFoundException — and one @RestControllerAdvice class is enough to answer both consistently, with the handler written exactly once.