What is RFC 9457 and what does a problem details response contain?
RFC 9457 defines a standard JSON body for HTTP API errors, served with the media type application/problem+json. It obsoletes RFC 7807 and keeps the same core format, so existing RFC 7807 clients continue to work. The newer RFC adds two things. First, it gives guidance on reporting multiple problems. If several problems share a type, return that type once and list the occurrences in an extension member. If the problems have different types, return the most relevant or urgent one. Second, it creates an IANA registry of common problem types. about:blank is the default type. When it is used, title should match the HTTP status phrase.
The standard members, shown with illustrative values for a failed order request:
| Member | Meaning | Example value |
|---|---|---|
type |
URI identifying the problem category (defaults to about:blank) |
/problems/insufficient-stock |
title |
Short summary that stays the same for every occurrence of this type | Insufficient stock |
status |
HTTP status code, repeated for convenience | 409 |
detail |
Explanation specific to this occurrence | Only 2 units of SKU-1138 remain |
instance |
URI identifying this specific occurrence | /orders/7f3a/attempts/1 |
extension, e.g. availableUnits |
Any additional member you define; clients must ignore extensions they don't recognise | 2 |
The format is useful because it gives every endpoint the same error contract. Clients branch on type rather than parsing message strings, and they can safely ignore extensions they don't understand. This matters most for backend and platform engineers whose APIs serve several clients, such as web, mobile and partner integrations, or who run several services behind one gateway. In those setups, inconsistent error shapes add parsing work for every consumer.
HTTP/1.1 409 Conflict
Content-Type: application/problem+json
Content-Language: en
{
"type": "/problems/insufficient-stock",
"title": "Insufficient stock",
"status": 409,
"detail": "Only 2 units of SKU-1138 remain",
"instance": "/orders/7f3a/attempts/1",
"availableUnits": 2
}
HTTP/1.1 404 Not Found
Content-Type: application/problem+json
{
"type": "about:blank",
"title": "Not Found",
"status": 404,
"detail": "No order with id 9c21 exists",
"instance": "/orders/9c21"
}
Two illustrative problem details responses: a custom problem type with an availableUnits extension member, and a generic error using the default about:blank type, where the title matches the HTTP status phrase.
Who should use Spring Boot problem details?
Use it if you build or consume HTTP APIs on Spring MVC or Spring WebFlux with Spring Boot 3 or later. ProblemDetail and the related types arrived in Spring Framework 6, the generation that Boot 3 is built on. The roles below get the most out of it:
- Backend engineers who own a public or multi-client API. When web, mobile and partner integrations call the same endpoints, one documented error shape removes a whole category of per-client questions about what a failure looks like.
- Platform teams standardizing many services. A shared
@RestControllerAdvice, a shared set oftypeURIs and a shared extension-member schema can ship as one internal library. Every service then emits the same contract without each team designing its own. - Client developers (frontend, mobile, integration). They write one error parser that switches on
typeor anerrorCodeextension. They don't need endpoint-specific parsing. - On-call and support engineers. A consistent body with a
traceIdandinstancegives them a direct handle from a user's error report to the server logs.
It is a weaker fit for endpoints called by a single co-deployed consumer, for APIs with an entrenched custom error format, and for gRPC or GraphQL. These cases are covered in the last section.
How does it work in Spring Boot?
In short, an exception is thrown, Spring resolves it to a ProblemDetail, and a message converter writes that object as application/problem+json. The exception can describe itself through ErrorResponse, or a @RestControllerAdvice can map it. Spring's Jackson support serializes the standard members and flattens any extension properties into top-level JSON members. Errors that happen before DispatcherServlet reaches a handler, such as security and filter failures, need their own hooks. The rest of this section shows the pieces.
Spring Framework provides four types that split the work between the response body and the exception that produces it.
| Type | Role | When you use it |
|---|---|---|
ProblemDetail |
Body model with type, title, status, detail, instance, plus a map for extension members |
Building a response body directly in a handler or advice |
ErrorResponse |
Interface an exception implements to supply its own status, headers and ProblemDetail |
Domain exceptions that should describe themselves |
ErrorResponseException |
Base class that already implements ErrorResponse |
Custom exceptions where you don't want to write the boilerplate |
ResponseEntityExceptionHandler |
Base class for an advice, with handlers for Spring MVC's own exceptions | A central @RestControllerAdvice that you extend |
The ErrorResponse contract keeps HTTP decisions out of a long if/else chain in the advice. The exception carries its status and problem type. The advice only applies cross-cutting concerns, such as logging or adding a trace ID.
Setting spring.mvc.problemdetails.enabled=true makes Boot register an advice based on ResponseEntityExceptionHandler. The WebFlux equivalent is spring.webflux.problemdetails.enabled=true. With either property on, built-in exceptions are rendered as application/problem+json instead of the default error map. Examples are an unsupported media type, a missing request parameter or a failed @Valid check. If you declare your own ResponseEntityExceptionHandler subclass, Boot's version backs off, so you won't end up with two competing handlers.
The advice only sees exceptions thrown after DispatcherServlet has selected a handler. Errors raised earlier take other paths:
request
│
▼
Servlet filters / Spring Security ── 401/403 → AuthenticationEntryPoint, AccessDeniedHandler
│ other filter exceptions → container → /error
▼
DispatcherServlet ─────────────────── no handler (404), media type, binding errors
│
▼
Handler (controller) ──────────────── domain exceptions, validation failures
│
▼
@RestControllerAdvice ─────────────── maps anything thrown by the handler or by MVC
│ (unhandled, or response.sendError)
▼
Error controller (/error) ─────────── fallback for everything that escaped the layers above
// Domain exception that describes itself: status, type and extra fields live here, not in the advice.
class OrderNotFoundException extends ErrorResponseException {
OrderNotFoundException(String orderId) {
super(HttpStatus.NOT_FOUND, problem(orderId), null);
}
private static ProblemDetail problem(String orderId) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(
HttpStatus.NOT_FOUND, "Order " + orderId + " does not exist");
pd.setType(URI.create("/problems/order-not-found"));
pd.setTitle("Order not found");
pd.setProperty("orderId", orderId); // extension member
return pd;
}
}
// Central advice. Because this subclass exists, Boot's own problem-details advice backs off.
// The inherited handlers already cover Spring MVC exceptions and any ErrorResponseException.
@RestControllerAdvice
class ApiExceptionHandler extends ResponseEntityExceptionHandler {
// Every response from this class flows through this method, so it is the
// single place for cross-cutting additions such as a trace ID.
@Override
protected ResponseEntity<Object> handleExceptionInternal(
Exception ex, Object body, HttpHeaders headers,
HttpStatusCode status, WebRequest request) {
if (body instanceof ProblemDetail pd) {
String traceId = MDC.get("traceId"); // SLF4J MDC, if your tracing populates it
if (traceId != null) {
pd.setProperty("traceId", traceId);
}
}
return super.handleExceptionInternal(ex, body, headers, status, request);
}
}
A self-describing exception built on ErrorResponseException, plus a ResponseEntityExceptionHandler subclass that replaces Boot's default advice and adds a trace ID to every ProblemDetail body (imports omitted for brevity).
How do you implement a central @RestControllerAdvice for domain errors?
Put all domain mappings in one class annotated with @RestControllerAdvice that extends ResponseEntityExceptionHandler. The base class already turns Spring MVC's own exceptions into ProblemDetail responses. Your subclass adds one @ExceptionHandler method per domain exception, such as OrderNotFoundException or InsufficientCreditException.
In each handler, start from ProblemDetail.forStatusAndDetail(status, detail) and then set the remaining fields yourself:
type: set it withsetTypeto a stable URI for that error class. The default isabout:blank, which tells the client nothing.title: set it withsetTitleto a fixed, human-readable summary for that type.instance: set it withsetInstanceto the request path or a resource URI, so a specific report can be traced to the request that produced it.
Add extension members with setProperty. Typical members are errorCode (for example ORDER_NOT_FOUND) and traceId, read from MDC or your tracing context. Spring's Jackson support serializes these properties as top-level JSON members next to status and title, not inside a nested properties object.
Clients should branch on type or errorCode. Treat detail as prose: it can be reworded, localized or made more precise without any notice. A client that parses it will break when the wording changes.
Add a final @ExceptionHandler(Exception.class) that returns a generic 500 problem with a fixed detail and the traceId. Log the full exception and stack trace on the server. Never copy ex.getMessage() into detail, because exception messages can expose SQL, internal hostnames or class names.
If you run several advice beans, order them explicitly with @Order. Spring checks advice beans in that order before it looks for the most specific exception match. As a result, a catch-all in a higher-priority advice shadows the specific handlers in every advice ranked below it.
Only one advice should extend ResponseEntityExceptionHandler. A second subclass registers the same MVC exception mappings again. Whichever advice ranks higher handles those exceptions, and the other copy is dead code that will drift from the active one.
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE) // explicit: checked before any other advice beans
public class ApiExceptionHandler extends ResponseEntityExceptionHandler {
// Only this advice extends the base class, so Spring MVC exceptions have one owner
private static final Logger log = LoggerFactory.getLogger(ApiExceptionHandler.class);
@ExceptionHandler(OrderNotFoundException.class)
ProblemDetail handleOrderNotFound(OrderNotFoundException ex, HttpServletRequest req) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND,
"Order " + ex.getOrderId() + " does not exist."); // prose for humans, not for parsing
return withCommonFields(pd, "order-not-found", "Order not found", "ORDER_NOT_FOUND", req);
}
// Catch-all: fixed detail for the client, full cause logged server-side only
@ExceptionHandler(Exception.class)
ProblemDetail handleUnexpected(Exception ex, HttpServletRequest req) {
log.error("Unhandled exception on {} {}", req.getMethod(), req.getRequestURI(), ex);
ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.INTERNAL_SERVER_ERROR,
"An unexpected error occurred. Quote the traceId when reporting it."); // never ex.getMessage()
return withCommonFields(pd, "internal-error", "Internal server error", "INTERNAL_ERROR", req);
}
private ProblemDetail withCommonFields(ProblemDetail pd, String slug, String title,
String errorCode, HttpServletRequest req) {
pd.setType(URI.create("/problems/" + slug)); // stable, replaces about:blank
pd.setTitle(title); // fixed per type
pd.setInstance(URI.create(req.getRequestURI())); // ties report to request
// Extension members serialize as top-level JSON members, e.g.
// {"type":"...","title":"Order not found","status":404,"detail":"...",
// "instance":"/orders/42","errorCode":"ORDER_NOT_FOUND","traceId":"4bf92f35..."}
pd.setProperty("errorCode", errorCode); // clients branch on this or on type
pd.setProperty("traceId", MDC.get("traceId"));
return pd;
}
}
A single ordered @RestControllerAdvice that extends ResponseEntityExceptionHandler, maps a domain exception to a ProblemDetail with deliberate type, title, instance and top-level errorCode/traceId members, and adds a catch-all that logs the cause without leaking it into detail.
How should validation errors be returned as a single problem?
The previous section's handler should be the only place handleMethodArgumentNotValid is overridden. A request body with five bad fields is one failure, not five, so it should produce one response. RFC 9457 says problem details are not designed to carry several unrelated problem types. When multiple problems share a type, the RFC recommends describing them in a single problem with an extension member. Model validation that way: one type such as a validation-failed URI, status 400, and an errors array. Each entry holds the field name or JSON pointer, a short reason, and the constraint code from FieldError.getCode(), such as NotBlank or Size. Leave out the rejected value. It can contain passwords or tokens and adds nothing clients can act on.
Validation of method parameters, such as @PathVariable or @RequestParam with constraints, does not arrive as MethodArgumentNotValidException. Depending on how method validation is wired, it surfaces as ConstraintViolationException or HandlerMethodValidationException. Map those to the same type and the same errors shape, so clients do not care where in the request the constraint was declared.
Resolve title and detail through MessageSource. ResponseEntityExceptionHandler looks up message codes derived from the exception, and you can supply your own codes for domain types. The per-field reason can be localized the same way. Treat every localized string as display-only. Its wording changes with the Accept-Language header and with each copy edit, so a client that branches on it will break. Clients should branch on type, the field identifier and code, which never change with locale.
@RestControllerAdvice
public class ApiExceptionHandler extends ResponseEntityExceptionHandler {
// One stable problem type for every validation failure, wherever the constraint lives
private static final URI VALIDATION_FAILED =
URI.create("/problems/validation-failed");
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex, HttpHeaders headers,
HttpStatusCode status, WebRequest request) {
Locale locale = LocaleContextHolder.getLocale();
MessageSource messages = getMessageSource();
// title/detail are display-only, resolved from codes such as
// problemDetail.title.org.springframework.web.bind.MethodArgumentNotValidException
ProblemDetail body = ex.updateAndGetBody(messages, locale);
body.setType(VALIDATION_FAILED);
// One problem, many fields: an extension member instead of several problems.
// The rejected value is deliberately left out; it may hold secrets.
List<Map<String, String>> errors = ex.getBindingResult().getFieldErrors().stream()
.map(fe -> Map.of(
"field", fe.getField(), // machine-readable, stable
"code", String.valueOf(fe.getCode()), // e.g. NotBlank, Size
"reason", messages != null // localized, for humans only
? messages.getMessage(fe, locale)
: String.valueOf(fe.getDefaultMessage())))
.toList();
body.setProperty("errors", errors);
return handleExceptionInternal(ex, body, headers, status, request);
}
}
An override of handleMethodArgumentNotValid that returns one RFC 9457 problem with a fixed type and an errors extension. Each entry carries a stable field name and constraint code, plus a reason resolved through MessageSource that is meant for display only.
How do you make filter, security and 404 errors use the same format?
@RestControllerAdvice only sees exceptions thrown while DispatcherServlet is invoking a handler. Anything that fails earlier, or is written directly to the response, never reaches it. That includes a servlet filter rejecting a request, Spring Security's ExceptionTranslationFilter delegating to its entry point or access-denied handler, and a request the container forwards to /error. These responses fall back to Spring Boot's default error JSON or an HTML page, so clients end up parsing two error formats.
| Error source | Why advice misses it | Where to hook in |
|---|---|---|
| Custom servlet filter | Runs before DispatcherServlet |
Catch in the filter, call the writer |
| Authentication failure (401) | Handled inside the security filter chain | Custom AuthenticationEntryPoint |
| Authorization failure (403) | Same | Custom AccessDeniedHandler |
| Unmapped path (404) | May be raised inside DispatcherServlet or rendered via the container's error path, depending on configuration |
Advice if raised as an exception, otherwise the error controller |
Container forward to /error |
Original exception is already gone | Custom ErrorController or ErrorAttributes |
Route all of these through one ProblemDetailWriter bean. It should accept a ProblemDetail and the HttpServletResponse, and serialize the problem with the application's ObjectMapper. With one writer, the type URIs, extension fields and redaction rules stay identical across all paths.
During error handling, do not let content negotiation fail. If the client's Accept header excludes application/problem+json, negotiation can raise a 406. That 406 hides the original 401 or 500. Instead, have the writer send application/problem+json regardless of Accept. HTTP permits sending a non-acceptable representation instead of returning 406. Switch to plain application/json only for known clients that reject the problem media type. The body is the same in both cases.
How do you design and version problem type URIs?
A type URI is a contract identifier. Clients branch on it, log it and alert on it, so it has to stay stable for the life of the API. Use a URI under a domain you control, for example a path such as /problems/insufficient-funds, and make it resolve to a page that explains the cause, the extension members and what the client should do. If you cannot host documentation, the URI must at least be unique.
Never reuse a type for a second meaning. Clients that handle insufficient-funds by prompting a top-up will do the wrong thing if the same type later covers frozen accounts. Changing what a type means, or removing an extension member it carries, is a breaking change, so version it like any other API change. Mint a new type and leave the old one documented until no clients depend on it.
| Approach | Client can branch on | Ongoing cost |
|---|---|---|
| Documented type URIs | Type plus extension members | Docs, review, deprecation process |
about:blank everywhere |
Status code only | None, but 409 or 422 becomes ambiguous |
Extension member names drift quickly across services, for example errors, violations and fieldErrors for the same concept. To prevent this, publish one shared schema or a small library that defines the member names and types, and have every service depend on it.
Treat switching on the framework defaults in an existing service as an API change. Built-in errors change both their body shape and their Content-Type, which breaks clients that parse the old format. Announce the change, check client logs for parsers that fail on the new format, and roll it out behind a configuration flag per environment.
How do you test the error contract with MockMvc or WebTestClient?
Treat the error format as a public API and give it its own test class. Each test should send a request that triggers a specific failure and then check three things: the Content-Type is application/problem+json, the type and status members match the documented values, and the extension members you promised are present. With MockMvc this is content().contentType(...) plus jsonPath(...) assertions. With WebTestClient it is expectHeader().contentType(...) plus expectBody().jsonPath(...).
Cover one case per failure path, because each path is produced by different code:
- Domain error: throw the exception from a stubbed service. Assert its
typeURI and any domain extension, such as an order ID. - Validation error: post an invalid body. Assert a single problem with a
400status and anerrorsarray containing a field name and a message for each failure. - Security errors: send one request with no credentials and one with insufficient credentials. Assert
401and403in problem format. Run these tests with the security filter chain active. If the tests bypass it, they pass while production returns the container's default error page. - Unmapped 404: request a path that no handler matches.
- Non-acceptable
Acceptheader: sendAccept: application/xmland assert406. Also pin down the body behavior you chose, so a framework upgrade cannot change it without a test failing.
In every case, assert that the correlation ID in the response header matches the one in the body.
These tests save time in two ways. Clients can write a single error parser against a format that the build enforces, so they don't need a separate parser for each endpoint. During incidents, a guaranteed correlation ID lets an engineer go from a client's error report straight to the matching server log line, without reconstructing what happened from timestamps.
How can problem details save engineering time?
The time savings come from removing repeated work rather than from any single feature:
- Less handler code on the server. With the Boot property enabled, or with a
ResponseEntityExceptionHandlersubclass, Spring MVC's own exceptions are already mapped to problem responses. Media type errors, missing parameters, binding failures and@Validfailures need no per-exception code. Domain exceptions built onErrorResponseExceptioncarry their own status and type, so adding a new error means writing one class rather than editing a centralif/elsechain. - One parser per client instead of one per service. Because every endpoint returns the same members, a client team writes error handling once and reuses it across all services. A new service is covered by that parser from its first release.
- Fewer contract discussions. The RFC answers the shape questions (field names, media type, how to report multiple problems), so design reviews focus on which
typevalues exist and what they mean. - Faster triage. A
traceIdandinstancein every body, including security and filter errors, let on-call engineers find the matching log entry directly, without reconstructing the request from timestamps. - Regressions caught in CI. The contract tests from the previous section fail the build when a change breaks the format. Without them, the break shows up later as a client bug report.
An illustrative estimate, using assumed inputs rather than measured results: assume 4 client applications consuming 6 services, and assume each client spends 3 hours writing and maintaining error handling for each service-specific error format. That is 4 × 6 × 3 = 72 hours. If a shared format means each client writes its parser once, at an assumed 5 hours each, the total is 4 × 5 = 20 hours, plus an assumed one-off 16 hours of platform work for the shared advice, type URIs and contract tests, giving 36 hours. Under these assumptions the shared format roughly halves the effort, and the gap widens with each added service or client. With fewer consumers, or one already-stable custom format, the balance can tip the other way, as the next section explains.
When should you avoid Spring Boot problem details, and what are the alternatives?
Problem details is not always the right default, and adopting it too early can cost more than it saves.
An established custom error format. If dozens of clients already parse an errorCode/errorMessage shape, switching to type/title/detail breaks every one of them. You would need a versioned rollout or content negotiation, and that work only pays off if you also gain new consumers who benefit from the standard.
Internal-only endpoints. For a health probe or an admin endpoint called by one service your team owns, Spring Boot's default error attributes are usually enough. A shared contract matters less when producer and consumer are deployed together.
gRPC and GraphQL. Both protocols have their own error models. gRPC uses status codes with structured details. GraphQL returns an errors array, often alongside a successful HTTP status. Wrapping either in RFC 9457 works against their client libraries.
| Option | Standardization | Client tooling | Implementation effort | Migration cost |
|---|---|---|---|---|
| RFC 9457 problem details | IETF standard | Generic parsers work | Moderate | High if replacing a live format |
| Custom error DTO | Team-specific | Hand-written per client | Low at first, grows over time | None if already in place |
| Default error attributes | Framework convention | Minimal | Near zero | Low |
| Protocol-native models | Protocol standard | Built into gRPC/GraphQL clients | Low | Not applicable |
Problem details pays off for new or public HTTP APIs consumed by several teams. Clients reuse one error parser instead of writing one per service. Support and on-call engineers also spend less time decoding inconsistent error bodies during triage.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to spring boot problem details, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.