RFC 9457 Problem Details for Error Responses in Spring
Return RFC 9457 problem details from a Spring Boot API: ProblemDetail, ErrorResponse, a ControllerAdvice, extension members and enabling it globally.

Each API invents its own error body, so every client writes special code. RFC 9457 (which replaced RFC 7807) standardizes one, and Spring supports it natively.
The format
{
"type": "https://api.javahacks.dev/problems/out-of-stock",
"title": "Out of stock",
"status": 409,
"detail": "Item A-1 has 0 units available",
"instance": "/orders/42",
"sku": "A-1"
}| Member | Meaning |
|---|---|
type | A URI that identifies the kind of problem (default about:blank) |
title | A short, stable summary |
status | The HTTP status |
detail | An explanation for this occurrence |
instance | A URI for this occurrence |
| extensions | Any other members, like sku |
The media type is application/problem+json. The type URI can link to documentation, which makes errors discoverable.
Turn it on for framework errors
spring.mvc.problemdetails.enabled=trueWith the property, Spring's own exceptions, such as HttpRequestMethodNotSupportedException (405) and MethodArgumentNotValidException, are rendered as problem details by the built-in ResponseEntityExceptionHandler. Without it, they use the default error JSON from Boot.
Handle your own exceptions
@RestControllerAdvice
class ApiErrors extends ResponseEntityExceptionHandler {
@ExceptionHandler(OutOfStockException.class)
ProblemDetail outOfStock(OutOfStockException e) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, e.getMessage());
problem.setTitle("Out of stock");
problem.setType(URI.create("https://api.javahacks.dev/problems/out-of-stock"));
problem.setProperty("sku", e.sku());
return problem;
}
}Returning a ProblemDetail is enough: Spring sets the status from it and the content type to application/problem+json. Extending ResponseEntityExceptionHandler gives problem details for all the standard MVC exceptions, with hooks you can override. For exceptions you throw from controllers, a class that implements ErrorResponse carries its own status and detail:
class OrderNotFound extends ErrorResponseException {
OrderNotFound(long id) {
super(HttpStatus.NOT_FOUND, ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, "order " + id), null);
}
}Validation errors
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatusCode status, WebRequest request) {
ProblemDetail problem = ex.getBody();
problem.setTitle("Validation failed");
problem.setProperty("errors", ex.getFieldErrors().stream()
.map(f -> Map.of("field", f.getField(), "message", String.valueOf(f.getDefaultMessage())))
.toList());
return handleExceptionInternal(ex, problem, headers, status, request);
}Clients get a stable errors array to display next to fields, the extension to the base format. The flow into this handler is described in returning clean validation errors.
What to put in each member
type: stable, documented, one per class of problem.title: the same for every occurrence of that type.detail: specific to this one, safe for clients to read. Never include SQL, stack traces or secrets.status: matches the response status, see status codes.
Use the traceId extension to link an error to your logs, which is more useful than internals.
Clients
A client reads Content-Type, and if it is application/problem+json, parses the standard members first and falls back to a generic message otherwise. Declare the format in your OpenAPI document, see documenting with OpenAPI.
Choosing the type URI
The type member identifies the kind of problem, and a clients' code should branch on it, and never on detail or title, which are for people and may change. Use a stable URI, and make it resolve to a page that explains the problem, for example https://api.example.com/problems/out-of-stock. If you do not want to host pages yet, a URI under a domain you control still works as an identifier, and about:blank means "no more information than the status code gives". Keep the set of types small and documented, since every type is a promise to clients.
Detail without leaking
The detail member describes this occurrence, and is the place where developers leak. A message such as ERROR: duplicate key value violates unique constraint "uk_user_email" gives an attacker the schema. Write detail as a sentence for the caller, "A user with this email already exists", generated by your code and not copied from an exception. Log the original exception with a correlation id, and put the id in the problem as an extension member, so support can find it, and the client sees nothing internal.
Extension members for validation errors
The format allows extra members, and validation is the main use. Add an errors array with one entry per invalid field, holding the field name, a code and a message:
{
"type": "https://api.example.com/problems/validation",
"title": "Validation failed",
"status": 400,
"errors": [{ "field": "email", "code": "invalid_format", "message": "Must be a valid email" }]
}A client can map the entries to form fields without parsing text. Use codes that stay stable across language changes, and translate the messages with the Accept-Language header if you serve several languages.
Content type and negotiation
The media type is application/problem+json. Spring sets it for ProblemDetail responses, and a client that sends Accept: application/json still gets it, since the +json suffix makes it compatible. Make sure that error responses from your gateway, your authentication filters and the framework's own 404 and 405 use the same format. An API in which the controllers answer with problem details and the security filter answers with an HTML page forces clients to handle two shapes, and the inconsistency is the first thing they complain about.
Internationalization of titles
Spring 6 can resolve problem titles and details from a MessageSource, using keys built from the exception class name, so translations live in the message bundles and not in code. Define the keys for the exceptions you raise, and keep the English text as the default. It is a small amount of work for an API with clients in more than one language, and it keeps the error text out of the Java source.
Handling problems in a client
A client library should turn a problem response into a typed exception that carries the status, the type, the detail and the extension members, and let the application branch on the type. Write one such class for the API and reuse it. Log the instance or the correlation id with every failure, since it is what you quote to the server team. Do not show detail to end users without thought: it is written for developers and may be too technical for a customer, so map known types to your own messages.
Evolving the error contract
Adding a new problem type is a compatible change if clients treat unknown types as a generic failure of that status. Renaming a type or changing the meaning of a status is breaking. Document each type with its status, its extension members and an example, and review the list when you add endpoints, so that the same condition is not given two different types by two teams. A short table in the API documentation, kept next to the code, does more for consistency than any guideline.
Where this does not apply
Errors outside the MVC layer, like those from a servlet filter or the web server, do not pass through the advice, and Spring Security has its own entry points for 401 and 403 that need configuring to emit problem details. The reference is RFC 9457, and the Spring error responses documentation covers the types.


