Card 05/ 07

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.

java
// 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());
}
text
STATUS -> 404
BODY -> specific handler: Ride not found with id: 100
run in a container — the Exception handler is declared first and still loses

Spring 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.