ProblemDetail
ProblemDetail is the body of an error response in the standard form of RFC 9457 (application/problem+json): a status, a type, a title, a detail, an instance and any extra fields. ErrorResponse, ErrorResponseException and ResponseStatusException are the errors that carry one.
Why
It gives every error of an API the same shape, so a client reads them all with the same code. The starter answers its own errors this way (a missing parameter, an invalid body, an unknown path). Return a ProblemDetail from a controller or an @ExceptionHandler, or throw an exception that carries one, to answer the application's own errors the same way.
Example
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';
class Book {
const Book({required this.isbn, required this.stock});
final String isbn;
final int stock;
}
// An application error that always has the same answer.
class OutOfStockException extends ErrorResponseException {
OutOfStockException(String isbn)
: super(
HttpStatus.conflict,
body: ProblemDetail(
HttpStatus.conflict,
type: Uri.parse('https://shop.example/problems/out-of-stock'),
title: 'Out of stock',
detail: 'No copy of $isbn is left',
properties: {'isbn': isbn},
),
);
}
@RestController()
@RequestMapping('/api/orders')
class OrderController {
// A status and a message: the quickest way.
@GetMapping('/{id}')
String find(@PathVariable() int id) =>
throw ResponseStatusException(HttpStatus.notFound, 'No order $id');
// A problem of the application's own type.
@PostMapping('/{isbn}')
String order(@PathVariable() String isbn) => throw OutOfStockException(isbn);
// Too many requests: 429 with a Retry-After header.
@PostMapping('/bulk')
String bulk() => throw ErrorResponseException(
HttpStatus.tooManyRequests,
headers: HttpHeaders()..set(HttpHeaders.retryAfterHeader, '30'),
body: ProblemDetail.forStatusAndDetail(
HttpStatus.tooManyRequests,
'Try again in 30 seconds',
),
);
// A ProblemDetail returned, not thrown.
@GetMapping('/{id}/invoice')
ProblemDetail invoice(@PathVariable() int id) =>
ProblemDetail.forStatusAndDetail(HttpStatus.notFound, 'No invoice yet');
}
POST /api/orders/978-0 → 409 application/problem+json
{"type":"https://shop.example/problems/out-of-stock","title":"Out of stock","status":409,
"detail":"No copy of 978-0 is left","instance":"/api/orders/978-0","isbn":"978-0"}
ProblemDetail
Constructors
| Constructor | Makes |
|---|---|
ProblemDetail(status, {type, title, detail, instance, properties}) |
a problem with any of the standard members; type defaults to about:blank |
ProblemDetail.forStatus(status) |
a problem with the status only; its title is the status's reason phrase |
ProblemDetail.forStatusAndDetail(status, detail) |
a problem with a status and a detail: the most common way |
ProblemDetail.fromJson(json) |
a problem read from decoded JSON, such as the body of an error a client received. Members other than the five standard ones go to properties; a missing status is read as 500. |
Fields
| Name | Type | Default | Meaning |
|---|---|---|---|
status |
int |
required | The HTTP status code. When the server writes the problem, the response gets this status. |
type |
Uri |
ProblemDetail.blankType (about:blank) |
A URI that names the kind of problem, for clients that tell problems apart by type. about:blank means the status says it all. |
title |
String? |
null |
A short summary of the kind of problem. null: the JSON has the status's reason phrase (Not Found). |
detail |
String? |
null |
An explanation of this occurrence for the client: No book 978-0. |
instance |
Uri? |
null |
A URI for this occurrence. The server sets it to the request path when it is null. |
properties |
Map<String, Object?> |
{} |
Extra members, written next to the standard ones; for example the errors of a failed validation. |
Members
| Member | Does |
|---|---|
setProperty(name, value) |
adds an extra member, replacing an earlier value |
effectiveTitle |
the title, or the status's reason phrase when it is null (null only for an unknown status) |
toJson() |
the JSON object: type, the effective title, status, detail and instance (leaving out nulls), then the properties |
ProblemDetail.blankType |
about:blank |
Rules:
- The JSON. Members are written in the order
type,title,status,detail,instance, then the properties. A property with a standard name (detail) replaces that member. Thepropertiesvalues are written withjsonEncode, so use JSON values there (strings, numbers, booleans, lists, maps). - The media type is
application/problem+json, with the problem'sstatusas the response status. AProblemDetailinside aResponseEntitygets the entity's status and keeps aContent-Typethe entity sets. @ResponseStatuson the method replaces the status of a returnedProblemDetail.- Keep the detail for the client. It is sent as it is. An exception's message may hold SQL, file names or values: do not copy it into the detail without thought.
ErrorResponse
ErrorResponse is the interface of an error that carries its own HTTP answer. When a controller throws one, the server answers with it instead of a 500.
| Member | Type | Meaning |
|---|---|---|
statusCode |
int |
The status of the answer. |
headers |
HttpHeaders |
Headers to add, such as Allow for a wrong method or WWW-Authenticate for a missing login. They replace headers of the same name, except Vary, whose names are added. |
body |
ProblemDetail |
The problem written as the body; its status is set to statusCode. |
Every error of the starter is one (see Errors). HandlerExceptionResolver beans return one (see HandlerExceptionResolver). Most applications throw ResponseStatusException or extend ErrorResponseException rather than implement the interface.
ErrorResponseException
An exception that is an ErrorResponse: the base class of the starter's own errors. Throw it when the answer needs more than a status and a message, such as headers or extra problem members; extend it for an application error that always has the same answer.
| Name | Type | Default | Meaning |
|---|---|---|---|
statusCode (positional) |
int |
required | The status of the answer. |
body |
ProblemDetail? |
a problem with the status only | The problem of the answer. |
headers |
HttpHeaders? |
no headers | Headers to add to the answer. |
cause |
Object? |
null |
The error that led to this one. It is never sent to the client. |
Its toString() is ClassName: status detail, as the logs show it.
ResponseStatusException
The quickest way to end a request with an error, from a controller or from code it calls: the server answers with the status and a problem whose detail is the reason.
| Name | Type | Default | Meaning |
|---|---|---|---|
statusCode (positional) |
int |
required | The status of the answer. |
reason (positional) |
String? |
null |
The problem's detail. null: no detail. |
cause (positional) |
Object? |
null |
The error that led to this one; not sent. |
@GetMapping('/books/{isbn}')
Future<Book> find(@PathVariable() String isbn) async =>
await books.findOrNull(isbn) ??
(throw ResponseStatusException(HttpStatus.notFound, 'No book $isbn'));
A ResponseStatusException of 500 or more (a 503 for maintenance) is logged as a warning without a stack trace, at most once every 10 seconds per type and status; below 500 at debug level.
On the client side
A Feign client (or any code that reads an error answer) turns the body back into a problem with ProblemDetail.fromJson(jsonDecode(body)), with the extra members in properties.
In Spring (Java)
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, "No copy left");
problem.setType(URI.create("https://shop.example/problems/out-of-stock"));
problem.setProperty("isbn", isbn);
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No book " + isbn);
Differences that matter:
- The fields are plain Dart fields (
problem.type = ...), not setters;propertiesis a mutable map. ProblemDetail.fromJsonreads a received problem; Spring uses Jackson for that.- Statuses are
ints (theHttpStatusconstants areints too), not anHttpStatusCodeobject.