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

ProblemDetail

A standard error format.

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

Every API used to invent its own error format. Now there's a standard, called problem details, and Spring supports it out of the box.

  • Everyone had their own
  • Now there's a standard
  • Problem details

Problem detail fields

Type is a link that identifies the kind of problem, and it's left out when there isn't one. Title is a short summary. Status repeats the HTTP status. Detail explains this case. And instance is the URL that failed. You can add your own fields too.

FieldExample
typea link (optional)
titleBook not found
status404
detailBook 9 was not found
instance/books/9

Returning a ProblemDetail

The handler returns a Problem Detail, made for four oh four, with our message. We set a short title. And we add an extra field, a tip. In the properties, problem details enabled, makes Spring's own errors use the format too. Run it. Our four oh four has a title, the status, the detail, and our tip. Its content type is application problem JSON. And Spring's own four oh five, for an unsupported method, uses the same format.

GlobalErrors.javajava
@RestControllerAdvice
public class GlobalErrors {

    @ExceptionHandler(BookNotFoundException.class)
    public ProblemDetail notFound(BookNotFoundException ex) {
        ProblemDetail problem = ProblemDetail.forStatusAndDetail(
            HttpStatus.NOT_FOUND, ex.getMessage());
        problem.setTitle("Book not found");
        problem.setProperty("tip", "GET /books lists every book");
        return problem;
    }
}
Output
$ curl -i localhost:8080/books/9
HTTP/1.1 404
Content-Type: application/problem+json

{
  "title":"Book not found",
  "status":404,
  "detail":"Book 9 was not found",
  "tip":"GET /books lists every book"
}
$ curl -X DELETE localhost:8080/books/1
{
  "title":"Method Not Allowed",
  "status":405,
  "detail":"Method 'DELETE' is not supported."
}
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 application.properties
spring.mvc.problemdetails.enabled=true
Also uses _curl.sh
curl -i localhost:8080/books/9
curl -X DELETE localhost:8080/books/1

Summary

Problem Detail is the standard error format, with type, title, status, detail, and instance. Spring can use it everywhere. Next, some practice.

Key takeaways
  • ProblemDetail
  • application/problem+json
  • problemdetails.enabled
Next up: Practice: Clean Errors — your turn