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:

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:

  1. the @ExceptionHandler methods of the controller whose method failed;
  2. the @ExceptionHandler methods of the @ControllerAdvice beans, in @Order; the first bean that has a handler for the error answers it;
  3. the HandlerExceptionResolver beans, in @Order; the first that returns an answer wins. They are not asked for an error that is already an ErrorResponse;
  4. the default answer, below.

Rules:

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:

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:

See also