@RestControllerAdvice
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
handle exceptions in one place.
Planned topics
@RestControllerAdviceis a class whose@ExceptionHandlermethods apply to all controllers.- Each handler maps an exception type to a response.
- Remove
try/catchfrom controllers; let exceptions travel up. - Order: specific handlers first; add a catch-all for
Exception. - Validation failures arrive as
MethodArgumentNotValidException.
Draft outline details
Demonstration
@RestControllerAdvice
class ApiExceptionHandler {
@ExceptionHandler(NotFoundException.class)
ProblemDetail notFound(NotFoundException ex) {
return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
}
}Check your understanding
Where should the try/catch for not-found live?
Show answer
Nowhere in controllers; the advice handles it.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.