Sub topic 11
Handling errors with @RestControllerAdvice and ProblemDetail
This chapter assumes you can write a @RestController, bind a @Valid @RequestBody DTO, and delegate to a service class. It covers how to turn exceptions into consistent, well-formed HTTP error responses.
Why errors need one shared format
Without any handling, an exception thrown in a controller reaches Spring Boot's default error handling. Clients then see a generic 500 page or a default JSON body whose shape differs between failure types. Callers cannot rely on that.
A good error strategy has three parts:
- The service layer throws domain exceptions that describe what went wrong, such as "book not found".
- One central component maps each exception to an HTTP status and a body.
- Every error body has the same shape, so clients write one error parser.
Spring supports this with @RestControllerAdvice and ProblemDetail.
ProblemDetail and RFC 9457
ProblemDetail is a Spring class (since Spring Framework 6) that models the "problem details" format from RFC 9457. This RFC replaced RFC 7807. The response uses the media type application/problem+json. The standard members are:
| Member | Meaning |
|---|---|
| `type` | A URI that identifies the kind of problem. Defaults to `about:blank`. |
| `title` | A short, human-readable summary of the problem type. |
| `status` | The HTTP status code. |
| `detail` | An explanation specific to this occurrence. |
| `instance` | A URI that identifies this occurrence. Spring fills it with the request path. |
You can also add custom members with setProperty. They appear as extra top-level fields in the JSON.
A domain exception and a global handler
Start with an unchecked exception that the service throws, and a class annotated with @RestControllerAdvice. This annotation combines @ControllerAdvice and @ResponseBody. Its @ExceptionHandler methods apply to every controller in the application, and their return values are written to the response body.
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 a missing book now produces this response:
{
"type": "about:blank",
"title": "Book not found",
"status": 404,
"detail": "No book with id 42",
"instance": "/api/books/42"
}The status line is 404 Not Found, and the Content-Type is application/problem+json. You did not have to build a ResponseEntity. Returning a ProblemDetail is enough, because its status field sets the response status.
How the request reaches the handler
The flow matters when you debug a handler that does not fire.
The DispatcherServlet catches the exception and asks its exception resolvers to handle it. The resolver for @ExceptionHandler methods checks the controller's own handlers first. It then checks the @ControllerAdvice beans. Among the handlers that match, the one with the closest exception type wins.
Handling validation failures
Chapter-level validation with @Valid @RequestBody throws MethodArgumentNotValidException when a constraint fails. That is a Spring MVC built-in exception. You have two ways to convert it into a ProblemDetail.
Option 1: turn on the built-in support
Spring Boot can render Spring MVC's own exceptions as problem details. Add one property:
spring.mvc.problemdetails.enabled=trueWith this property, failures such as a malformed JSON body, an unsupported media type, a missing parameter, or a failed @Valid check return application/problem+json. The status is 400, 415, and so on, as appropriate. Under the hood, Boot registers a ResponseEntityExceptionHandler subclass as a @ControllerAdvice bean.
The default body for a validation failure has a generic detail such as "Invalid request content." It does not list which fields failed.
Option 2: extend ResponseEntityExceptionHandler
To add field-level details, extend ResponseEntityExceptionHandler in your own advice class and override the method for the exception you care about. Do not also enable the property in this case. Boot's auto-configured advice would conflict with yours, and two such beans cause ambiguity.
@RestControllerAdvice
public class ApiExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(BookNotFoundException.class)
public ProblemDetail handleNotFound(BookNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Book not found");
return problem;
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatusCode status,
WebRequest request) {
Map<String, String> errors = new LinkedHashMap<>();
for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
errors.putIfAbsent(fieldError.getField(), fieldError.getDefaultMessage());
}
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.BAD_REQUEST, "Request validation failed");
problem.setTitle("Invalid request");
problem.setProperty("errors", errors);
return handleExceptionInternal(ex, problem, headers, status, request);
}
}A request with a blank title now returns:
{
"type": "about:blank",
"title": "Invalid request",
"status": 400,
"detail": "Request validation failed",
"instance": "/api/books",
"errors": {
"title": "must not be blank"
}
}The putIfAbsent call keeps the first message when one field fails several constraints. Choose a different merge rule if you want all of the messages.
Choosing between handler styles
| Approach | Use it when | Trade-off |
|---|---|---|
| `@ExceptionHandler` in an advice | Mapping your own domain exceptions | You must write one method per exception family. |
| `spring.mvc.problemdetails.enabled=true` | Spring MVC's built-in errors should be problem details with no custom code | Validation details are generic. |
| Extending `ResponseEntityExceptionHandler` | You need to customize built-in errors, such as field errors | You take responsibility for the full set of overridden methods. |
| `@ResponseStatus` on the exception class | A quick mapping with no custom body | You cannot add fields or a title. |
Edge cases and common mistakes
A catch-all handler hides bugs
A handler for Exception.class guarantees a consistent body for unexpected failures, but it needs care. Log the exception with its stack trace, and return a generic message. Never put ex.getMessage() in the response for unexpected errors, because it can leak internal details such as SQL or file paths.
@ExceptionHandler(Exception.class)
public ProblemDetail handleUnexpected(Exception ex) {
log.error("Unhandled exception", ex);
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected error occurred");
problem.setTitle("Internal server error");
return problem;
}Place this in the same advice class. The most specific handler still wins, so the catch-all only receives exceptions that nothing else matches. If your class extends ResponseEntityExceptionHandler, Spring MVC's own exceptions are handled by its inherited handler method, so they do not fall through to the catch-all.
Exceptions inside filters are not caught
@RestControllerAdvice only sees exceptions thrown during controller handling. An exception thrown in a servlet filter, such as a custom authentication filter, happens before the DispatcherServlet is involved. The advice does not handle it. Spring Security has its own entry points for those cases.
Do not use exceptions as the only control flow
For an expected "not found" result, throwing is fine because it keeps the controller short. Avoid it for conditions the caller can easily check, such as an empty search result. An empty list with status 200 is the correct answer there, not a 404.
Choose the right status code
- 400 for a malformed request or failed validation.
- 404 when the identified resource does not exist.
- 409 for a conflict with current state, such as a duplicate unique value.
- 422 is sometimes used for semantic validation errors. Pick one convention for validation and apply it everywhere.
- 500 only for failures that are the server's fault.
Set a meaningful type URI
about:blank is valid when the status code alone describes the problem. If clients need to branch on the kind of error, set a stable type:
problem.setType(URI.create("https://api.example.com/problems/book-not-found"));Clients can then match on type instead of parsing the human-readable title or detail, which may change.
Exercises
Exercise
A request body fails a @NotBlank constraint on a @Valid @RequestBody parameter. Which exception does Spring MVC throw, and what status does the built-in problem-details support return?
Show answer
It throws MethodArgumentNotValidException. With spring.mvc.problemdetails.enabled=true, the response is 400 Bad Request with the media type application/problem+json.
Exercise
Your advice class has handlers for RuntimeException and for BookNotFoundException, which extends RuntimeException. A BookNotFoundException is thrown. Which handler runs, and why?
Show answer
The BookNotFoundException handler runs. Spring picks the handler whose declared exception type is closest to the thrown exception's type in the class hierarchy.
Exercise
Write a handler method for a DuplicateIsbnException that returns a 409 ProblemDetail with the title "Duplicate ISBN" and a custom property isbn that holds the value from ex.getIsbn().
Show answer
@ExceptionHandler(DuplicateIsbnException.class) public ProblemDetail handleDuplicate(DuplicateIsbnException ex) { ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, ex.getMessage()); problem.setTitle("Duplicate ISBN"); problem.setProperty("isbn", ex.getIsbn()); return problem; }