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.
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.
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
@RestControllerAdvicepublic 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
@Servicepublic 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
@RestControllerpublic 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(); }}