Sub topic 9
A standard error body with ProblemDetail
This chapter assumes you can write a Spring Boot controller and a @RestControllerAdvice class, and that you know the earlier chapters' OrderNotFoundException and ApiExceptionHandler. It covers the shape of the error body those handlers return and how to shape it deliberately.
Why a standard body
Without a convention, every endpoint invents its own error JSON. One returns {"error": "not found"}, another returns {"message": "...", "code": 17}. Clients then need special parsing for each case.
RFC 9457 ("Problem Details for HTTP APIs", which replaces RFC 7807) defines one JSON shape for errors. Spring Framework 6 and Spring Boot 3 support it through the ProblemDetail class. You build a ProblemDetail, return it from a handler, and Spring serializes it with the media type application/problem+json.
The standard members
A problem detail has five standard members. All are optional in the RFC, but you should set most of them.
| Member | Meaning | Spring accessor |
|---|---|---|
| `type` | A URI that identifies the kind of problem. Defaults to `about:blank`. | `setType(URI)` |
| `title` | A short summary of the problem type. It should not change between occurrences. | `setTitle(String)` |
| `status` | The HTTP status code. | `forStatus(...)` |
| `detail` | An explanation of this specific occurrence. | `setDetail(String)` |
| `instance` | A URI that identifies this occurrence. | `setInstance(URI)` |
Anything else you add is an extension member. setProperty(name, value) stores it, and Jackson writes it at the top level of the JSON object, next to the standard members. It is not nested under a properties key.
The earlier handler used setProperty("orderId", ...). For GET /orders/99 the response looks like this:
{
"type": "about:blank",
"title": "Order not found",
"status": 404,
"detail": "Order 99 was not found",
"instance": "/orders/99",
"orderId": 99
}When a handler returns a ProblemDetail, Spring uses its status field as the HTTP status. It also fills instance with the request path if you left it empty.
Title versus detail
Keep the difference between title and detail consistent, because clients may rely on it.
titledescribes the category. "Order not found" is the same for every missing order.detaildescribes this case. "Order 99 was not found" names the order.- Machine-readable data, such as the id, goes in an extension member. Clients should not have to parse
detail.
Giving problems a type
With type left at about:blank, the RFC says the problem has no meaning beyond its HTTP status, and title should be the standard status reason phrase. That is acceptable for generic errors. For domain errors, a specific type lets clients branch on a stable identifier. The status code alone is too coarse. A 409 could mean a locked order or a duplicate order.
The type URI is an identifier first. It does not have to resolve, but it is good practice to make it point to documentation.
A small helper keeps the URIs and the shape consistent:
package com.example.orders;
import java.net.URI;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
final class Problems {
private static final String BASE = "https://api.example.com/problems/";
private Problems() {}
static ProblemDetail of(HttpStatus status, String slug, String title, String detail) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(status, detail);
problem.setType(URI.create(BASE + slug));
problem.setTitle(title);
return problem;
}
}The OrderNotFoundException handler in ApiExceptionHandler can then become:
@ExceptionHandler(OrderNotFoundException.class)
public ProblemDetail handleOrderNotFound(OrderNotFoundException ex) {
ProblemDetail problem = Problems.of(HttpStatus.NOT_FOUND, "order-not-found",
"Order not found", ex.getMessage());
problem.setProperty("orderId", ex.getOrderId());
return problem;
}Now type is https://api.example.com/problems/order-not-found. Clients can switch on it without comparing title strings.
How the pieces fit
The diagram shows where a ProblemDetail comes from and how it reaches the client.
Problem details for Spring's own exceptions
Spring MVC raises its own exceptions for malformed JSON, unsupported media types, missing parameters and unmatched methods. By default these produce the old /error response, not a problem detail. There are two ways to get consistent bodies for them.
- Set
spring.mvc.problemdetails.enabled=true, as in the properties file from the chapter onserver.error.*. Spring Boot then registers a handler that extendsResponseEntityExceptionHandler. - Extend
ResponseEntityExceptionHandlerin your own@RestControllerAdvice, asApiExceptionHandleralready does.
Do both and the property has no effect, because Boot's handler backs off when it finds another ResponseEntityExceptionHandler bean. Two such advice classes also compete with each other, so keep exactly one.
ResponseEntityExceptionHandler has one overridable method per MVC exception. The validation chapter's handleMethodArgumentNotValid is one of them. Each override receives the exception and returns a ResponseEntity<Object>. Use them to add extension members or change titles for exceptions you did not write.
Exceptions that carry their own problem
Spring defines an ErrorResponse interface for exceptions that know how to describe themselves. ErrorResponseException is the ready-made base class. The exception builds its ProblemDetail at the throw site, so no handler is needed:
package com.example.orders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.ErrorResponseException;
public class OrderLockedException extends ErrorResponseException {
public OrderLockedException(long orderId) {
super(HttpStatus.CONFLICT, asProblem(orderId), null);
}
private static ProblemDetail asProblem(long orderId) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(
HttpStatus.CONFLICT, "Order " + orderId + " is locked");
problem.setTitle("Order locked");
problem.setProperty("orderId", orderId);
return problem;
}
}ResponseEntityExceptionHandler handles ErrorResponseException automatically, so this works with your advice class or with the Boot property.
Choosing between the two designs
| Approach | Strength | Cost |
|---|---|---|
| Plain exception plus `@ExceptionHandler` | Domain code has no HTTP types. All wording lives in one class. | You write a handler for each exception. |
| `ErrorResponseException` subclass | No handler needed. The exception and its response stay together. | Domain exceptions now depend on Spring Web and HTTP status codes. |
For a service where the domain layer is separate from the web layer, prefer the first. For a small application, the second saves code.
Localizing and customizing messages
ErrorResponse supports message-code resolution. Spring looks for title and detail entries in a MessageSource under keys derived from the exception class, such as problemDetail.title.com.example.orders.OrderLockedException. If you need translated errors, this is the supported path. Without a matching message code, the values you set in code are used.
Gotchas
- Do not mix error shapes. If one handler returns a
ProblemDetailand another returns aMap, clients see two formats. Route every handler through the same helper. - Extension names must not collide. Do not call
setProperty("status", ...)orsetProperty("title", ...). You would create duplicate JSON keys. - The
/errorfallback is separate. Errors that never reach MVC, such as a failure in a servlet filter, still go throughBasicErrorController. Its body has the old format (timestamp,status,error,path) unless you customize it. - Do not put internals in
detail. Never passex.getMessage()from an arbitrary exception. ASQLExceptionmessage can expose table names. The 500 handler in this tutorial uses a fixed sentence for that reason.
Verifying the body
Use MockMvc to assert the exact members, as in the earlier test class. You can also check the media type:
mockMvc.perform(get("/orders/99"))
.andExpect(status().isNotFound())
.andExpect(content().contentTypeCompatibleWith("application/problem+json"))
.andExpect(jsonPath("$.type").value("https://api.example.com/problems/order-not-found"))
.andExpect(jsonPath("$.instance").value("/orders/99"));This needs a static import of MockMvcResultMatchers.content.
Exercise
A handler returns ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, "Order 7 is locked") and calls problem.setProperty("orderId", 7). Which top-level members appear in the JSON, and what HTTP status does the client receive?
Show answer
The JSON contains type ("about:blank", since none was set), title (the reason phrase "Conflict" is filled in only if you set it, so it may be absent), status (409), detail ("Order 7 is locked"), instance (the request path) and the extension member orderId (7), all at the top level. The HTTP status is 409, because Spring takes the response status from the ProblemDetail's status field.
Exercise
You enable spring.mvc.problemdetails.enabled=true and also have an @RestControllerAdvice that extends ResponseEntityExceptionHandler. Which handler produces the body for a malformed JSON request, and why?
Show answer
Your own advice class does. Boot's ProblemDetailsExceptionHandler is registered only when no other ResponseEntityExceptionHandler bean exists, so with your subclass present the property has no effect on which class handles the exception.