Errors
Every error is answered with a problem: a JSON body in the form of RFC 9457 (application/problem+json) with the status, a title and a detail. The application changes the answer with @ExceptionHandler methods, @ControllerAdvice beans and HandlerExceptionResolver beans.
Why
Clients need to read errors as reliably as successes. With one shape for every error, from an unknown path to an invalid body to the application's own "book not found", a client handles them all with the same code. The starter answers its own errors this way, and gives the application three places to answer its exceptions the same way:
- an @ExceptionHandler method on a controller, for the errors of that controller;
- an
@ExceptionHandlermethod on a @ControllerAdvice bean, for every controller; - a HandlerExceptionResolver bean, for what no handler answers; it is how a library maps its own exceptions.
Example
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';
class Book {
const Book({required this.isbn, required this.title});
final String isbn;
final String title;
}
class BookNotFoundException implements Exception {
BookNotFoundException(this.isbn);
final String isbn;
}
@RestController()
@RequestMapping('/api/books')
class BookController {
@GetMapping('/{isbn}')
Book find(@PathVariable() String isbn) => throw BookNotFoundException(isbn);
// Quick: a status and a message, from anywhere.
@GetMapping('/{isbn}/cover')
String cover(@PathVariable() String isbn) =>
throw ResponseStatusException(HttpStatus.notFound, 'No cover for $isbn');
}
@RestControllerAdvice()
class ApiErrors {
// Every controller's BookNotFoundException is a 404 problem.
@ExceptionHandler()
@ResponseStatus(HttpStatus.notFound)
ProblemDetail notFound(BookNotFoundException e) =>
ProblemDetail.forStatusAndDetail(HttpStatus.notFound, 'No book ${e.isbn}')
..setProperty('isbn', e.isbn);
}
GET /api/books/123 → 404 application/problem+json
{"type":"about:blank","title":"Not Found","status":404,"detail":"No book 123","instance":"/api/books/123","isbn":"123"}
GET /api/books/123/cover → 404 application/problem+json
{"type":"about:blank","title":"Not Found","status":404,"detail":"No cover for 123","instance":"/api/books/123/cover"}
GET /nowhere → 404 application/problem+json
{"type":"about:blank","title":"Not Found","status":404,"detail":"No endpoint GET /nowhere.","instance":"/nowhere"}
The way of an error
When a request fails, the starter tries, in this order:
- the
@ExceptionHandlermethods of the controller whose method failed; - the
@ExceptionHandlermethods of the@ControllerAdvicebeans, in@Order; the first bean that has a handler for the error answers it; - the
HandlerExceptionResolverbeans, in@Order; the first that returns an answer wins. They are not asked for an error that is already anErrorResponse; - the default answer, below.
Rules:
- Errors before a method was chosen (the 404, 405, 406 and 415 of the router, the errors of other handler mappings such as WebSocket handshakes) skip step 1 and the advice beans narrowed to some controllers.
- An error thrown by a filter skips steps 1 to 3 and gets the default answer.
- A handler that fails is logged as a warning. When a controller's
@ExceptionHandlerthrows, the advice beans (those not narrowed to some controllers) and the resolvers can still answer the original error; when an advice's handler throws, the error gets the default answer. A resolver that throws is skipped, and the next resolver is asked. - A committed response cannot get an error answer: the error is logged and the connection is dropped without finishing the response, as Tomcat does.
server.request-timeout. When the request deadline passes before the answer starts, the client gets a 503 problem (AsyncRequestTimeoutException, detailThe request did not complete in time.). Exception handlers do not see it, since the handler still runs (see Timeouts).
The default answers
| Cause | Status | Exception | Detail |
|---|---|---|---|
no mapping for the path, or a path outside server.context-path |
404 | NoHandlerFoundException |
No endpoint GET /x. |
| the path is mapped, but not for this method | 405, with Allow |
HttpRequestMethodNotSupportedException |
Method 'DELETE' is not supported. |
a Content-Type not in consumes, not JSON (or missing) for a @RequestBody object, or not a media type at all |
415, with Accept |
HttpMediaTypeNotSupportedException |
Content-Type 'text/xml' is not supported. |
nothing in produces (or JSON, for an object) suits Accept |
406 | HttpMediaTypeNotAcceptableException |
Acceptable representations: [application/json]. |
| a required value missing | 400 | MissingRequestValueException |
Required parameter 'q' is not present. (also header, cookie, path variable, part) |
| a value that does not convert | 400 | MethodArgumentTypeMismatchException |
Failed to convert 'page' with value: 'two' |
a body that is missing, malformed, of the wrong shape, or a form with a bad % escape |
400 | HttpMessageNotReadableException |
Failed to read request |
@Valid violations |
400, with errors |
MethodArgumentNotValidException |
Invalid request content. |
unmet headers conditions |
400 | ResponseStatusException |
Unsatisfied header conditions |
a request body above server.max-http-request-body-size |
413 | PayloadTooLargeErrorException |
The request body exceeds 10485760 bytes. |
an upload above spring.web.multipart.max-file-size or max-request-size, or with more than max-part-count parts |
413 | MaxUploadSizeExceededException |
Maximum upload size exceeded: ... |
a malformed multipart request, or @RequestPart on a request that is not multipart |
400 | MultipartRequestException |
Failed to parse multipart request: ... |
a request body that sends nothing for server.connection-timeout (60 s) |
408 | ResponseStatusException |
The request body did not arrive in time |
the request deadline (server.request-timeout) passed |
503 | AsyncRequestTimeoutException |
The request did not complete in time. |
a new session above server.session.max-sessions |
503 | TooManyActiveSessionsException |
Too many active sessions |
a non-nullable Principal parameter without a user |
401 | ResponseStatusException |
|
throw ResponseStatusException(status, reason) |
its status | its reason | |
an ErrorResponse or ErrorResponseException |
its status, with its headers | its problem | |
an error a HandlerExceptionResolver answers |
its status, with its headers | its problem | |
| any other exception | 500 | none: the client learns nothing of the exception |
The validation answer lists the violations:
{"type":"about:blank","title":"Bad Request","status":400,"detail":"Invalid request content.","instance":"/api/books",
"errors":[{"field":"title","message":"must not be blank","rejectedValue":""}]}
Each field error has field, message and rejectedValue; an error of the whole object has object and message. Messages come from the application's MessageSource, else the constraint's default message.
All these exceptions are ErrorResponseExceptions and can be caught by an @ExceptionHandler to answer them another way (see @ExceptionHandler). They are exported by package:spring_boot_starter_web/spring_boot_starter_web.dart.
Answered before any filter
The server itself answers some requests before they reach the filters or a handler:
| Request | Status |
|---|---|
a method other than GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS and TRACE |
501 Unsupported method |
no client certificate with server.ssl.client-auth=need |
403 A client certificate is required |
a missing or malformed Host, or one that is not the host of an absolute target |
400 |
an encoded /, \ or NUL in the path (%2F, %5C, %00) |
400 |
a . or .. segment behind matrix parameters (/files/..;/secret) |
400 |
a % escape in the path or the query that is not UTF-8 (/%FF) |
400 |
These answers are problems too.
Plain-text answers
Two kinds of answers are plain text instead of problems, as in Spring:
- a refused CORS request:
403with the bodyInvalid CORS request(see CORS); - a WebSocket handshake that the WebSocket starter refuses:
403for an origin or aHandshakeInterceptor,400for a request that asks for no upgrade or a path variable that does not convert (see WebSocket).
Logging
Errors are logged under spring.web.mvc:
| Error | Level | Line |
|---|---|---|
an ErrorResponse below 500 (a 404, a 400, ...) |
debug | Resolved [NoHandlerFoundException: No endpoint GET /x.] |
an ErrorResponse of 500 and more (a ResponseStatusException(503), a refused session) |
warning, without a stack trace, at most once every 10 seconds for the same type and status | Request GET /x answered with ResponseStatusException: 503 Down for maintenance, with (4 more of these not logged since the last warning) when some were left out (those are logged at debug level) |
| any other exception (a 500) | error, with its stack trace | Request GET /x failed |
| an error after the response was committed | warning, with its stack trace | Request GET /x failed after the response was committed |
an @ExceptionHandler that throws |
warning | The @ExceptionHandler ApiErrors.notFound failed handling ... |
a HandlerExceptionResolver that answers (whatever the status) |
debug | Resolved [<the error>] as 409 by RoomTakenResolver |
a HandlerExceptionResolver that throws |
warning | The HandlerExceptionResolver RoomTakenResolver failed handling ... |
Paths and texts in log lines are made safe: line breaks become <EOL>, control characters ?. With logging.level.spring.web.servlet.DispatcherServlet=debug, every request is logged too (GET "/api/books", parameters={masked} and Completed 404 Not Found); spring.mvc.log-request-details=true shows the parameters and, at trace level, the headers, with credentials always masked.
In Spring (Java)
@RestControllerAdvice
class ApiErrors {
@ExceptionHandler
@ResponseStatus(HttpStatus.NOT_FOUND)
ProblemDetail notFound(BookNotFoundException e) {
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, "No book " + e.getIsbn());
problem.setProperty("isbn", e.getIsbn());
return problem;
}
}
Differences that matter:
- Errors are always
ProblemDetails. Spring Boot's default is the/errorJSON (timestamp,status,error,path) unlessspring.mvc.problemdetails.enabled=true; here there is no/errorendpoint and noErrorController. @ResponseStatuson an exception class is not read: throw aResponseStatusException, extendErrorResponseException, or write a handler.- One
MissingRequestValueExceptionstands for Spring'sMissingServletRequestParameterException,MissingRequestHeaderException,MissingRequestCookieException,MissingPathVariableExceptionandMissingServletRequestPartException. - A 5xx answer an exception asks for is logged as a warning at most once every 10 seconds per kind.