Sub topic 9
A standard error body with ProblemDetail
This chapter assumes you can write a Spring MVC controller and know the HTTP status codes. It also assumes you have seen @RestControllerAdvice from the previous chapter. Here you will standardize the JSON that your handlers return.
Why a standard body
Without a convention, every endpoint tends to invent its own error JSON, such as {"error": "..."} in one place and {"message": "...", "code": 7} in another. Clients then need custom parsing for each case. RFC 9457 (which replaces RFC 7807) defines a common shape called a problem detail. Spring 6 and Spring Boot 3 support it through the ProblemDetail class.
The members of a problem detail
| Member | Meaning | Spring setter |
|---|---|---|
| `type` | A URI that identifies the kind of problem. It defaults to `about:blank`. | `setType` |
| `title` | A short summary that stays the same for every occurrence of this problem type. | `setTitle` |
| `status` | The HTTP status code. | set by the factory method |
| `detail` | An explanation of this specific occurrence. | set by the factory method |
| `instance` | A URI for this occurrence. Spring fills in the request path if you leave it unset. | `setInstance` |
Extra members are allowed. You add them with setProperty(name, value), and Jackson writes them as top-level fields next to the standard ones.
Returning a ProblemDetail
A handler method can return a ProblemDetail directly. Spring writes it with the content type application/problem+json and uses the status field as the response status. This is the handler from the previous chapter:
@ExceptionHandler(OrderNotFoundException.class)
public ProblemDetail handleOrderNotFound(OrderNotFoundException ex) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Order not found");
problem.setProperty("orderId", ex.getOrderId());
return problem;
}A request for GET /orders/99 then produces this body:
{
"type": "about:blank",
"title": "Order not found",
"status": 404,
"detail": "Order 99 was not found",
"instance": "/orders/99",
"orderId": 99
}Clients can read orderId without parsing the detail text. That is why the exception carries the id as a field.
Giving problems a type
about:blank means "no more information than the status code". For problems that clients should react to, set a stable URI:
problem.setType(URI.create("https://api.example.com/problems/order-not-found"));The URI does not have to resolve, but it is good practice to point it at documentation. Clients can then branch on type instead of on the title text.
Covering Spring's own exceptions
Your handlers cover your own exceptions. Spring MVC also raises exceptions itself, such as a malformed JSON body, an unsupported media type, or a missing parameter. To turn those into problem details, do one of two things:
- Extend
ResponseEntityExceptionHandlerin your@RestControllerAdvice, asApiExceptionHandlerdoes. - Set
spring.mvc.problemdetails.enabled=true, which makes Boot register an equivalent advice for you.
Use one approach, not both. Boot's advice backs off when it finds your own ResponseEntityExceptionHandler subclass.
The diagram shows where ProblemDetail fits in the flow.
Common errors
- Mismatched status.
ProblemDetail.forStatus(...)sets the body field only. If you wrap it in aResponseEntitywith a different status, the body and the HTTP status disagree. Return theProblemDetailalone, or use the same status in both places. - Leaking internals in
detail. Passingex.getMessage()is fine for your own exceptions. It is not fine for unexpected ones, which is why the generic handler uses a fixed text. - Changing the title per occurrence. The title should describe the problem type. Put occurrence-specific text in
detail. - Reserved names. Do not use
type,title,status,detailorinstanceas property names.
Exercise
A client receives a 404 problem detail and needs to show the missing order's id. Which member should hold the id, and why not parse it out of detail?
Show answer
Add it as an extension member with problem.setProperty("orderId", id), which appears as a top-level orderId field. The detail text is meant for people and may change wording, so parsing it breaks clients.