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