Sub topic 11
Handling errors with @RestControllerAdvice and ProblemDetail
This chapter assumes you can write a @RestController, bind a @RequestBody, and validate it with @Valid. It also assumes you know basic HTTP status codes. Here you will turn exceptions into consistent JSON error responses in one place.
Why handle errors globally
Without handling, an uncaught exception in a controller produces Spring Boot's default error body or a bare 500. If each controller catches exceptions itself, the format drifts and the code fills with try/catch blocks.
A class annotated with @RestControllerAdvice applies to every controller. Inside it, each @ExceptionHandler method maps one exception type to a response. Controllers and services then just throw.
ProblemDetail
ProblemDetail is Spring's class for the RFC 9457 "problem details" format, a standard JSON shape for HTTP errors. Its main fields are:
| Field | Meaning |
|---|---|
| `type` | A URI that identifies the kind of problem. Defaults to `about:blank`. |
| `title` | A short summary of the problem type. |
| `status` | The HTTP status code. |
| `detail` | An explanation of this specific occurrence. |
| `instance` | A URI for this occurrence. Spring sets it to the request path. |
The response uses the media type application/problem+json.
A domain exception and a handler
The service throws a plain runtime exception. The advice class converts it into a 404.
public class BookNotFoundException extends RuntimeException {
public BookNotFoundException(long id) {
super("No book with id " + id);
}
}
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(BookNotFoundException.class)
public ProblemDetail handleNotFound(BookNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Book not found");
return problem;
}
}A request for GET /api/books/99 now returns status 404 with a body like this:
{
"type": "about:blank",
"title": "Book not found",
"status": 404,
"detail": "No book with id 99",
"instance": "/api/books/99"
}The handler returns a ProblemDetail directly, and Spring uses its status field as the HTTP status. You do not need to wrap it in a ResponseEntity.
Built-in Spring MVC errors
Spring MVC raises its own exceptions, such as MethodArgumentNotValidException when @Valid fails, or HttpMessageNotReadableException for malformed JSON. By default these produce Boot's standard error body. Turn on problem details for them with one property:
spring.mvc.problemdetails.enabled=trueWith this set, a failed @Valid check returns a 400 ProblemDetail without any handler of your own. Note that the default body names the failure but does not list each field error. If clients need per-field messages, add a handler for MethodArgumentNotValidException and attach them with problem.setProperty("errors", ...).
Common errors
- Handler never runs. The advice class must be a Spring bean in a package that component scanning covers. Check that it sits under your application's main package.
- Wrong status. If you return a
ProblemDetailbuilt with the wrongHttpStatus, the client sees that status. The exception type does not decide it. - Catch-all handlers hide the framework's errors. A handler for
Exception.classalso catches Spring's own exceptions, such as a missing resource, and turns them into 500s. Prefer specific exception types, or extendResponseEntityExceptionHandlerif you add a catch-all. - Leaking internals. Do not put stack traces or raw exception messages from unexpected errors into
detail. Log them, and return a generic message.
Exercise
A client sends malformed JSON to a POST endpoint. You have spring.mvc.problemdetails.enabled=true and no handler for HttpMessageNotReadableException. What status and media type does the client get, and why?
Show answer
The client gets a 400 response with media type application/problem+json. The property makes Spring MVC render its own built-in exceptions as ProblemDetail, and HttpMessageNotReadableException maps to 400 Bad Request.
Exercise
Write a handler method signature that returns a 409 ProblemDetail for a hypothetical DuplicateIsbnException, using the advice class from this chapter.
Show answer
@ExceptionHandler(DuplicateIsbnException.class) public ProblemDetail handleDuplicate(DuplicateIsbnException ex) { ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, ex.getMessage()); problem.setTitle("Duplicate ISBN"); return problem; }