AI Hints
Home›Spring Boot Tutorial›@RestControllerAdvice, ProblemDetail and Practice: Clean Errors
Spring Boot · Lesson 79 of 120

@RestControllerAdvice

Handle errors everywhere.

⏱ 2 min read▶ Video at 1:46:02🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

An app has many controllers. We don't want to copy the same error handlers into each one. A controller advice handles errors for all of them, in one place.

  • Many controllers
  • Don't copy handlers
  • One place for all

How it works

At Rest Controller Advice marks a class that helps every controller. Its at Exception Handler methods catch exceptions, from any controller. So all error handling lives in one class. And controllers stay clean, with only the happy path.

keyvalue
@RestControllerAdvicehelps every controller
@ExceptionHandlercatches from anywhere
Resultone error class
Controllersonly the happy path

A global error class

Global errors is our advice class. The first handler turns Book Not Found Exception into four oh four, with a small JSON body. The second handles validation errors, like before. The controller has no error code at all. Run it. Book nine gets four oh four, with a clear message. And the blank title gets its field error.

GlobalErrors.javajava
@RestControllerAdvice
public class GlobalErrors {

    @ExceptionHandler(BookNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Map<String, String> notFound(BookNotFoundException ex) {
        return Map.of("error", ex.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, String> invalid(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new TreeMap<>();
        ex.getBindingResult().getFieldErrors()
          .forEach(e -> errors.put(e.getField(), e.getDefaultMessage()));
        return errors;
    }
}
Output
$ curl -i localhost:8080/books/9
HTTP/1.1 404
Content-Type: application/json

{"error":"Book 9 was not found"}
$ curl --json '{"title":"","author":"Herbert","price":9.99}' localhost:8080/books
{"title":"must not be blank"}
Also uses BookNotFoundException.java
public class BookNotFoundException extends RuntimeException {

    public BookNotFoundException(long id) {
        super("Book " + id + " was not found");
    }
}
Also uses BookService.java
@Service
public class BookService {

    private final Map<Long, String> titles = Map.of(1L, "Dune", 2L, "Circe");

    public String title(long id) {
        String title = titles.get(id);
        if (title == null) {
            throw new BookNotFoundException(id);
        }
        return title;
    }
}
Also uses NewBook.java
public record NewBook(
    @NotBlank String title,
    @NotBlank String author,
    @Positive double price
) {}
Also uses BookController.java
@RestController
public class BookController {

    private final BookService service;

    public BookController(BookService service) { this.service = service; }

    @GetMapping("/books/{id}")
    public String one(@PathVariable long id) { return service.title(id); }

    @PostMapping("/books")
    public String add(@Valid @RequestBody NewBook book) { return "Saved: " + book.title(); }
}
Also uses _curl.sh
curl -i localhost:8080/books/9
curl --json '{"title":"","author":"Herbert","price":9.99}' localhost:8080/books

Summary

At Rest Controller Advice collects exception handlers for the whole app, so controllers stay clean. Next, Problem Detail, a standard error format.

Key takeaways
  • @RestControllerAdvice
  • One error class
  • Clean controllers
Next up: ProblemDetail — a standard error format