When at Valid fails, Spring throws a Method Argument Not Valid Exception. At Exception Handler marks a method that catches it. The exception holds a list of field errors. And whatever our handler returns, becomes the response.
The handler catches validation failures, and answers four hundred. It builds a map, from each field, to its message. A tree map keeps the fields in alphabetical order. Run it. The first request gets four hundred, listing the bad price, and the blank title. The second is missing two fields, and the messages say so.
BookController.javajava
@RestControllerpublic class BookController { @PostMapping("/books") public String add(@Valid @RequestBody NewBook book) { return "Saved: " + book.title(); } @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 --json '{"title":"","author":"Herbert","price":-5}' localhost:8080/books
HTTP/1.1 400
Content-Type: application/json
{"price":"must be greater than 0","title":"must not be blank"}
$ curl --json '{"price":9.99}' localhost:8080/books
{"author":"must not be blank","title":"must not be blank"}
Also uses NewBook.java
public record NewBook( @NotBlank String title, @NotBlank String author, @Positive double price) {}
Every constraint takes a message, written for humans. Here, each rule explains what the client should do. Run it. The same request now gets our friendly messages.
NewBook.javajava
public record NewBook( @NotBlank(message = "Every book needs a title") String title, @NotBlank(message = "Please tell us the author") String author, @Positive(message = "Price must be more than zero") double price) {}
Output
{"author":"Please tell us the author","title":"Every book needs a title"}
Also uses BookController.java
@RestControllerpublic class BookController { @PostMapping("/books") public String add(@Valid @RequestBody NewBook book) { return "Saved: " + book.title(); } @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; }}
At Exception Handler catches validation failures, so we can return each field, and its message. Custom messages make them friendly. Next, custom exceptions.