Error handling
@ControllerAdvice, RFC 9457 Problem Details, mapping exceptions to responses, and never leaking a stack trace or an entity name.
An error response is part of your API, and it is the part clients write the most code against — because the happy path is one shape and the failures are many. If each failure has its own shape, every client grows a pile of special cases with your service's name on it.
This lesson is one handler, one shape, everywhere.
What Spring gives you, and why it is not enough
The previous lesson ended here. Three fields failed validation:
$ curl -i -X POST /customers -d '{"name":"","email":"not-an-email","age":12}'
HTTP/1.1 400
Content-Type: application/json
{"timestamp":"2026-09-12T10:29:11.016+00:00","status":400,"error":"Bad Request","path":"/customers"}The status is right. The body tells the client nothing it did not already know. A form cannot show a field error; a log cannot say what was rejected.
And an unhandled exception is worse, in the other direction:
$ curl -i /boom
HTTP/1.1 500
{"timestamp":"...","status":500,"error":"Internal Server Error","path":"/boom"}There is no way for the caller to say what went wrong to a support engineer, and no way for the support engineer to find it. In a default Spring Boot setup with include-stacktrace turned up, the opposite problem appears — the client receives your class names, your package structure and your library versions.
One @RestControllerAdvice
Adding a single class changes both, for every endpoint, with no change to any controller:
@RestControllerAdvice
public class Problems {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, Object>> invalid(MethodArgumentNotValidException e) {
List<Map<String, String>> errors = new ArrayList<>();
e.getBindingResult().getFieldErrors().forEach(f -> {
Map<String, String> m = new LinkedHashMap<>();
m.put("field", f.getField());
m.put("message", f.getDefaultMessage());
errors.add(m);
});
Map<String, Object> body = new LinkedHashMap<>();
body.put("type", "https://api.example.com/problems/validation-failed");
body.put("title", "Validation failed");
body.put("status", 422);
body.put("detail", errors.size() + " field(s) were rejected");
body.put("instance", "/customers");
body.put("errors", errors);
return ResponseEntity.status(422)
.contentType(MediaType.parseMediaType("application/problem+json"))
.body(body);
}
}The same request, unchanged:
HTTP/1.1 422
Content-Type: application/problem+json
{"type":"https://api.example.com/problems/validation-failed",
"title":"Validation failed",
"status":422,
"detail":"3 field(s) were rejected",
"instance":"/customers",
"errors":[{"field":"name","message":"name is required"},
{"field":"email","message":"must be a well-formed email address"},
{"field":"age","message":"must be 18 or older"}]}Every rejected field, named, with the message the constraint declared. A front end can highlight three inputs from that without knowing anything about your service.
Problem Details is the shape, and it already exists
That body is not invented. RFC 9457 Problem Details for HTTP APIs defines exactly these fields, and using it means clients that already understand the format need no special casing:
| Field | What goes in it |
|---|---|
type | a URI identifying the kind of problem — the stable thing to branch on |
title | a short human-readable summary of the type |
status | the HTTP status, repeated so the body is self-contained |
detail | what went wrong this time |
instance | which request it was |
Plus any extra members you need — errors above is one. The media type is application/problem+json, and sending it is how a client knows to expect this shape rather than your normal response.
The field to design carefully is type. It is the machine-readable one: clients branch on it, so it must stay stable even when you reword title and detail. A client matching on the text of detail is a client you will break with a typo fix.
What never leaves the server
The second handler is the one that protects you:
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> unexpected(Exception e) {
String correlationId = UUID.randomUUID().toString();
log.error("{} unhandled", correlationId, e); // the detail goes HERE
Map<String, Object> body = new LinkedHashMap<>();
body.put("type", "about:blank");
body.put("title", "Internal Server Error");
body.put("status", 500);
body.put("detail", "The request could not be completed. Quote this id if you contact support.");
body.put("correlationId", correlationId);
return ResponseEntity.status(500)
.contentType(MediaType.parseMediaType("application/problem+json"))
.body(body);
}The client gets this:
HTTP/1.1 500
Content-Type: application/problem+json
{"type":"about:blank","title":"Internal Server Error","status":500,
"detail":"The request could not be completed. Quote this id if you contact support.",
"correlationId":"9cc8a9d9-6fee-481a-bc56-74506683f44e"}And the log gets this:
### logged: 9cc8a9d9-6fee-481a-bc56-74506683f44e java.lang.IllegalStateException: the database is on fireSame id, both sides. A user quotes eight characters and an engineer finds the exact request. Nothing about your internals crossed the wire.
The list of what must never appear in an error body: stack traces, exception class names, SQL, table or column names, file paths, library versions, another user's data, and the reason an authentication attempt failed. That last one is worth spelling out — "no such user" and "wrong password" are different answers, and returning different ones tells an attacker which emails are registered.
Mapping the exception hierarchy
Domain exceptions get their own handlers, so the controller never decides a status code:
@ExceptionHandler(OrderNotFoundException.class)
public ResponseEntity<...> notFound(OrderNotFoundException e) { ... } // 404
@ExceptionHandler(InsufficientStockException.class)
public ResponseEntity<...> conflict(InsufficientStockException e) { ... } // 409Two rules keep this from sprawling. Handle the most specific type you can — Spring picks the closest match, so a handler for Exception is the net beneath the others and not a replacement for them. And do not let a persistence exception escape: DataIntegrityViolationException reaching the generic handler produces a 500 for what is usually a 409 with a perfectly good explanation, and its message contains your constraint names.
Remember too that the previous lesson left two paths into the same wall: a rejected body throws MethodArgumentNotValidException, a rejected parameter throws ConstraintViolationException. Both need a handler, and both should produce the same shape — a client should not be able to tell from the response which mechanism rejected it.
Under the hood: how Spring picks which @ExceptionHandler runs
"Handle the most specific type you can" is not a style preference — it names a real algorithm. When an exception propagates out of a controller, ExceptionHandlerExceptionResolver asks every @ControllerAdvice/@RestControllerAdvice bean's ExceptionHandlerMethodResolver for a match: it walks up the thrown exception's class hierarchy — the exact class, then its superclass, then its superclass, and so on to Throwable — and at each step checks whether any @ExceptionHandler on that advice declares that exact type. The first hierarchy level with a match wins, which is a precise way of saying "nearest ancestor", not "most recently declared" or "declared first in the file" — declaration order in the source has no effect on which handler is chosen. If two @ExceptionHandler methods on the same advice bean declare the same exception type (directly, or by both matching at the same hierarchy depth through an ambiguous listing), Spring cannot pick one and throws IllegalStateException when the advice bean is built — an ambiguous mapping fails at startup, not silently at request time.
This is exactly why a handler for the broad Exception.class never shadows a handler for OrderNotFoundException even though Exception is technically "in the hierarchy" of every exception: OrderNotFoundException itself is a closer ancestor of the thrown exception than Exception is (distance zero versus some larger distance), so it is found first in the walk. The catch-all is correctly named "the net beneath the others" earlier in this lesson — the algorithm is why that phrase is literally true rather than just a helpful mental model.
ResponseEntityExceptionHandler (Spring's own base class, which the framework's built-in advice extends) applies the identical mechanism to Spring's own exceptions — HttpMessageNotReadableException maps to 400, NoHandlerFoundException to 404, and so on — via a table of ExceptionHandler methods keyed exactly the way your own Problems class's methods are. Your custom advice and Spring's built-in one compose through the same resolver; a handler you declare for a Spring exception type overrides the built-in one because your bean is consulted by the same nearest-ancestor rule.
Try it yourself
Work out which handler fires
An advice class declares handlers for Exception, for DataAccessException (Spring's root exception for database-layer failures), and for DataIntegrityViolationException (a subclass of DataAccessException, thrown on a unique-constraint violation). A controller lets a DataIntegrityViolationException propagate — nobody catches it. Using the nearest-ancestor rule above, which handler runs, and does it matter that Exception was declared first in the file?
Why "nearest ancestor" makes the file order irrelevant
The DataIntegrityViolationException handler runs. The resolver walks the thrown exception's own hierarchy starting from its exact class — DataIntegrityViolationException itself — and stops at the first level where a declared handler matches; that is a distance of zero, versus DataAccessException at distance one and Exception at some larger distance up the hierarchy. Declaration order in the source file has no bearing on this at all, because the resolver is walking the exception's hierarchy, not the advice class's method list — this is the same algorithm this lesson's "handle the most specific type you can" rule names, just traced through a three-level example instead of two.
Misconceptions
- "Declaring a handler for
Exceptionwill intercept everything, so more specific handlers below it are dead code." The resolver always prefers the nearest match in the thrown exception's hierarchy, regardless of where in the file (or even which advice bean) each handler is declared — a specific handler is never shadowed by a broader one declared "before" it. - "
ProblemDetail(Spring 6/Boot 3's built-in type) makes a hand-rolledMap-based Problem Details body unnecessary everywhere." It removes boilerplate for Spring's own exceptions viaResponseEntityExceptionHandler, but a domain exception likeInsufficientStockExceptionstill needs its own@ExceptionHandlerto decide the status and populatetype/detailmeaningfully —ProblemDetailis a shape you populate, not a mapping from your own exception types to statuses.
Sources
- RFC 9457, Problem Details for HTTP APIs (obsoletes RFC 7807).
- Spring Framework reference documentation —
@ExceptionHandler,ExceptionHandlerExceptionResolver, andResponseEntityExceptionHandler. - RFC 7231, HTTP/1.1: Semantics and Content — status code definitions the mapping ultimately targets.