1. Concept library
  2. Java & Spring Boot
  3. Module 7: REST APIs

Concept

Error handling with advice

A @RestControllerAdvice turns exceptions into consistent HTTP responses in one place: the status, a stable error code and a message. Controllers then do not need try and catch at all.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what @RestControllerAdvice centralises
  2. Map a domain exception to a status and a stable error code
  3. Spot the catch-all handler that leaks internals to clients

In practice

A few lines that show Error handling with advice doing its job.

Java
@RestControllerAdvice
class ApiErrors {
    @ExceptionHandler(NotFoundException.class)
    ProblemDetail notFound(NotFoundException e) {
        var problem = ProblemDetail.forStatus(HttpStatus.NOT_FOUND);
        problem.setDetail(e.getMessage());
        return problem;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    ProblemDetail invalid(MethodArgumentNotValidException e) { /* field errors */ }
}

The common mistake

Watch for

A catch-all handler that returns the exception message for every Throwable. Internal details and stack traces end up in client responses; map known exceptions and return a generic 500 for the rest.

What to know first

Your roadmap puts these before Error handling with advice, unless you already know them.

How it stays learned

Once a session shows you understand Error handling with advice, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled
Previous in the module← Request validation