Skip to content
Ameen Abozaid
Planned lessonJNR-015-L03

@RestControllerAdvice

  • Lesson 3 of 6
  • Junior
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

  • @RestControllerAdvice is a class whose @ExceptionHandler methods apply to all controllers.
  • Each handler maps an exception type to a response.
  • Remove try/catch from controllers; let exceptions travel up.
  • Order: specific handlers first; add a catch-all for Exception.
  • Validation failures arrive as MethodArgumentNotValidException.
Draft outline details

Demonstration

java
@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.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.