AI Hints
Home›Spring Boot Tutorial›Validation Errors, Custom Exceptions and @ResponseStatus
Spring Boot · Lesson 76 of 120

Validation Errors

Tell the client what is wrong.

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

A four hundred alone isn't helpful. The client needs to know which fields were wrong, and why. Let's send that back.

  • 400 isn't enough
  • Which fields?
  • Why?

How it works

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.

keyvalue
FailureMethodArgumentNotValidException
Catch it@ExceptionHandler
Insidea list of field errors
Returnthe response body

A helpful 400

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
@RestController
public 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
) {}
Also uses _curl.sh
curl -i --json '{"title":"","author":"Herbert","price":-5}' localhost:8080/books
curl --json '{"price":9.99}' localhost:8080/books

Friendlier messages

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
@RestController
public 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;
    }
}
Also uses _curl.sh
curl --json '{"price":9.99}' localhost:8080/books

Summary

At Exception Handler catches validation failures, so we can return each field, and its message. Custom messages make them friendly. Next, custom exceptions.

Key takeaways
  • @ExceptionHandler
  • Field → message
  • message = "..."
Next up: Custom Exceptions — name your problems