Card 07/ 07

RecapDifficulty: Advanced1 min

Recap: Handling Errors Consistently

Custom exceptions, one central handler, the right status, and a body a client can act on.

Handling errors consistently comes down to the five ideas below, each listed with the card that covers it.

What the topic established, and which card it was on
The ideaWhere
Consistency means one exception per failure, one place that handles it, and one body shapeConsistent Error Handling in a REST API
A custom unchecked exception plus an @ExceptionHandler maps one failure to one responseError Handling Example: A Custom Exception and Its Handler
@RestControllerAdvice makes one handler answer for every controllerError Handling Example: One @RestControllerAdvice for Every Controller
404, 400, 401 and 409 each make a different claim about what happenedHTTP Status Codes for Errors: 400 vs 401 vs 404 vs 409
The most specific handler wins, whatever the declaration orderException Handler Selection: The Most Specific Type Wins

Put together: throw a named exception, handle it once in an advice class, answer with the status that matches, and return the same body shape every time.