AI Hints
Home›Spring Boot Tutorial›Project: The Controller, Validation and Errors and Security
Spring Boot · Lesson 116 of 120

Project: Validation and Errors

Clean answers for bad input.

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

Clients will send bad input, and ask for books that don't exist. Our API should answer clearly, in one standard format.

  • Bad input
  • Missing books
  • One clear format

Two kinds of error

Validation errors come from at Valid, when a rule fails. Not found errors come from our own exception. A rest controller advice handles both, in one place. And both answer as problem details, the standard error format.

keyvalue
Bad input@Valid → MethodArgumentNotValidException
MissingBookNotFoundException
One place@RestControllerAdvice
FormatProblemDetail

ApiErrors.java

Not found becomes a four oh four problem. Invalid input becomes a four hundred problem. We add an errors list, one message per failed field, sorted. Run it. The blank title, and the negative price, are both listed. And book ninety nine gives a clean four oh four.

ApiErrors.javajava
@RestControllerAdvice
public class ApiErrors {

    @ExceptionHandler(BookNotFoundException.class)
    public ProblemDetail notFound(BookNotFoundException ex) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ProblemDetail invalid(MethodArgumentNotValidException ex) {
        var pd = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Invalid input");
        pd.setProperty("errors", ex.getFieldErrors().stream()
                .map(e -> e.getField() + " " + e.getDefaultMessage()).sorted().toList());
        return pd;
    }
}
Output
$ curl --json '{"title":"","author":"Ann","price":-1}' localhost:8080/books
{
  "title":"Bad Request",
  "status":400,
  "detail":"Invalid input",
  "errors":["price must be greater than 0","title must not be blank"]
}
$ curl localhost:8080/books/99
{"title":"Not Found","status":404,"detail":"Book 99 was not found"}
Also uses Book.java
@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String author;
    private double price;

    protected Book() {}
    public Book(String title, String author, double price) {
        this.title = title; this.author = author; this.price = price;
    }
    public Long getId() { return id; }
    public String getTitle() { return title; }
    public String getAuthor() { return author; }
    public double getPrice() { return price; }
    public void setTitle(String title) { this.title = title; }
    public void setAuthor(String author) { this.author = author; }
    public void setPrice(double price) { this.price = price; }
}
Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {

    List<Book> findByAuthorContainingIgnoreCase(String author);
}
Also uses CreateBook.java
public record CreateBook(
    @NotBlank String title,
    @NotBlank String author,
    @Positive double price
) {}
Also uses BookResponse.java
public record BookResponse(Long id, String title, String author, double price) {

    static BookResponse from(Book b) {
        return new BookResponse(b.getId(), b.getTitle(), b.getAuthor(), b.getPrice());
    }
}
Also uses NewPrice.java
public record NewPrice(@Positive double price) {}
Also uses BookNotFoundException.java
@ResponseStatus(HttpStatus.NOT_FOUND)
public class BookNotFoundException extends RuntimeException {
    public BookNotFoundException(long id) { super("Book " + id + " was not found"); }
}
Also uses data.sql
INSERT INTO book (title, author, price) VALUES
  ('Dune', 'Frank Herbert', 9.99),
  ('The Hobbit', 'J.R.R. Tolkien', 8.99),
  ('Circe', 'Madeline Miller', 10.99),
  ('Children of Dune', 'Frank Herbert', 8.49),
  ('Song of Achilles', 'Madeline Miller', 9.49),
  ('The Fellowship of the Ring', 'J.R.R. Tolkien', 11.99),
  ('Emma', 'Jane Austen', 6.99),
  ('Persuasion', 'Jane Austen', 7.49);
Also uses application.properties
spring.jpa.defer-datasource-initialization=true
Also uses BookService.java
@Service
@Transactional
public class BookService {

    private final BookRepository books;

    public BookService(BookRepository books) { this.books = books; }

    @Transactional(readOnly = true)
    public List<BookResponse> search(String author) {
        List<Book> found = author == null ? books.findAll()
                                          : books.findByAuthorContainingIgnoreCase(author);
        return found.stream().map(BookResponse::from).toList();
    }

    @Transactional(readOnly = true)
    public BookResponse byId(long id) { return BookResponse.from(find(id)); }

    public BookResponse create(CreateBook req) {
        Book saved = books.save(new Book(req.title(), req.author(), req.price()));
        return BookResponse.from(saved);
    }

    public BookResponse changePrice(long id, double price) {
        Book book = find(id);
        book.setPrice(price);
        return BookResponse.from(book);
    }

    public void delete(long id) { books.delete(find(id)); }

    private Book find(long id) {
        return books.findById(id).orElseThrow(() -> new BookNotFoundException(id));
    }
}
Also uses BookController.java
@RestController
@RequestMapping("/books")
public class BookController {

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

    @GetMapping
    public List<BookResponse> list(@RequestParam(required = false) String author) {
        return service.search(author);
    }

    @GetMapping("/{id}")
    public BookResponse one(@PathVariable long id) { return service.byId(id); }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public BookResponse add(@Valid @RequestBody CreateBook req) {
        return service.create(req);
    }

    @PutMapping("/{id}/price")
    public BookResponse price(@PathVariable long id, @Valid @RequestBody NewPrice p) {
        return service.changePrice(id, p.price());
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable long id) { service.delete(id); }
}
Also uses _curl.sh
curl --json '{"title":"","author":"Ann","price":-1}' localhost:8080/books
curl localhost:8080/books/99

Validating the price

New Price has one rule, the price must be positive. The PUT endpoint uses at Valid, so the same advice handles it. Run it. A price of zero is rejected, with a clear message.

NewPrice.javajava
public record NewPrice(@Positive double price) {}
Output
{
  "title":"Bad Request",
  "status":400,
  "detail":"Invalid input",
  "errors":["price must be greater than 0"]
}
Also uses Book.java
@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String author;
    private double price;

    protected Book() {}
    public Book(String title, String author, double price) {
        this.title = title; this.author = author; this.price = price;
    }
    public Long getId() { return id; }
    public String getTitle() { return title; }
    public String getAuthor() { return author; }
    public double getPrice() { return price; }
    public void setTitle(String title) { this.title = title; }
    public void setAuthor(String author) { this.author = author; }
    public void setPrice(double price) { this.price = price; }
}
Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {

    List<Book> findByAuthorContainingIgnoreCase(String author);
}
Also uses CreateBook.java
public record CreateBook(
    @NotBlank String title,
    @NotBlank String author,
    @Positive double price
) {}
Also uses BookResponse.java
public record BookResponse(Long id, String title, String author, double price) {

    static BookResponse from(Book b) {
        return new BookResponse(b.getId(), b.getTitle(), b.getAuthor(), b.getPrice());
    }
}
Also uses BookNotFoundException.java
@ResponseStatus(HttpStatus.NOT_FOUND)
public class BookNotFoundException extends RuntimeException {
    public BookNotFoundException(long id) { super("Book " + id + " was not found"); }
}
Also uses data.sql
INSERT INTO book (title, author, price) VALUES
  ('Dune', 'Frank Herbert', 9.99),
  ('The Hobbit', 'J.R.R. Tolkien', 8.99),
  ('Circe', 'Madeline Miller', 10.99),
  ('Children of Dune', 'Frank Herbert', 8.49),
  ('Song of Achilles', 'Madeline Miller', 9.49),
  ('The Fellowship of the Ring', 'J.R.R. Tolkien', 11.99),
  ('Emma', 'Jane Austen', 6.99),
  ('Persuasion', 'Jane Austen', 7.49);
Also uses application.properties
spring.jpa.defer-datasource-initialization=true
Also uses BookService.java
@Service
@Transactional
public class BookService {

    private final BookRepository books;

    public BookService(BookRepository books) { this.books = books; }

    @Transactional(readOnly = true)
    public List<BookResponse> search(String author) {
        List<Book> found = author == null ? books.findAll()
                                          : books.findByAuthorContainingIgnoreCase(author);
        return found.stream().map(BookResponse::from).toList();
    }

    @Transactional(readOnly = true)
    public BookResponse byId(long id) { return BookResponse.from(find(id)); }

    public BookResponse create(CreateBook req) {
        Book saved = books.save(new Book(req.title(), req.author(), req.price()));
        return BookResponse.from(saved);
    }

    public BookResponse changePrice(long id, double price) {
        Book book = find(id);
        book.setPrice(price);
        return BookResponse.from(book);
    }

    public void delete(long id) { books.delete(find(id)); }

    private Book find(long id) {
        return books.findById(id).orElseThrow(() -> new BookNotFoundException(id));
    }
}
Also uses BookController.java
@RestController
@RequestMapping("/books")
public class BookController {

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

    @GetMapping
    public List<BookResponse> list(@RequestParam(required = false) String author) {
        return service.search(author);
    }

    @GetMapping("/{id}")
    public BookResponse one(@PathVariable long id) { return service.byId(id); }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public BookResponse add(@Valid @RequestBody CreateBook req) {
        return service.create(req);
    }

    @PutMapping("/{id}/price")
    public BookResponse price(@PathVariable long id, @Valid @RequestBody NewPrice p) {
        return service.changePrice(id, p.price());
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable long id) { service.delete(id); }
}
Also uses ApiErrors.java
@RestControllerAdvice
public class ApiErrors {

    @ExceptionHandler(BookNotFoundException.class)
    public ProblemDetail notFound(BookNotFoundException ex) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ProblemDetail invalid(MethodArgumentNotValidException ex) {
        var pd = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Invalid input");
        pd.setProperty("errors", ex.getFieldErrors().stream()
                .map(e -> e.getField() + " " + e.getDefaultMessage()).sorted().toList());
        return pd;
    }
}
Also uses _curl.sh
curl -X PUT --json '{"price":0}' localhost:8080/books/1/price

Summary

A rest controller advice turns validation errors, and missing books, into clear problem details. Next, security.

Key takeaways
  • @Valid
  • @RestControllerAdvice
  • ProblemDetail
Next up: Project: Security — who may do what