Card 05/ 07
All 7 cards
GotchaDifficulty: Advanced1 min
The Generic Handler That Doesn't Win
Declare a handler for Exception before a handler for RideNotFoundException, in the same class, and throw a RideNotFoundException. The specific one still answers — not the one declared first.
// Generic handler declared BEFORE the specific one, on purpose.
@ExceptionHandler(Exception.class)
ResponseEntity<String> handleAll(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("generic handler: " + ex.getMessage());
}
@ExceptionHandler(RideNotFoundException.class)
ResponseEntity<String> handleNotFound(RideNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("specific handler: " + ex.getMessage());
}STATUS -> 404
BODY -> specific handler: Ride not found with id: 100Spring resolves @ExceptionHandler methods by matching the most specific exception type, not by which one appears first in the source file. Assuming declaration order decides the winner is the natural guess and it's the wrong one — which matters, because a generic handler declared "first" for readability never actually shadows a more specific one, however it looks on the page.