エラー

すべてのエラーは problem で応答されます。これは RFC 9457 の形式 (application/problem+json) の JSON ボディで、ステータス、タイトル、詳細を持ちます。アプリケーションは @ExceptionHandler メソッド、@ControllerAdvice Bean、HandlerExceptionResolver Bean で応答を変更します。

使う理由

クライアントは、成功と同じくらい確実にエラーを読める必要があります。未知のパスから不正なボディ、アプリケーション独自の「本が見つからない」まで、すべてのエラーが一つの形をしていれば、クライアントは同じコードでそれらすべてを扱えます。スターターは自身のエラーをこの形で応答し、アプリケーションが自分の例外を同じ形で応答するための場所を三つ用意しています。

例

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);

  // 手軽な方法: どこからでもステータスとメッセージを返す。
  @GetMapping('/{isbn}/cover')
  String cover(@PathVariable() String isbn) =>
      throw ResponseStatusException(HttpStatus.notFound, 'No cover for $isbn');
}

@RestControllerAdvice()
class ApiErrors {
  // すべてのコントローラーの BookNotFoundException は 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"}

エラーの流れ

リクエストが失敗すると、スターターは次の順で試します。

  1. 失敗したメソッドを持つコントローラーの @ExceptionHandler メソッド。
  2. @ControllerAdvice Bean の @ExceptionHandler メソッド (@Order 順)。そのエラーのハンドラーを持つ最初の Bean が応答します。
  3. HandlerExceptionResolver Bean (@Order 順)。最初に応答を返したものが採用されます。すでに ErrorResponse であるエラーについては問い合わせられません。
  4. 後述のデフォルトの応答。

ルール:

デフォルトの応答

原因 ステータス 例外 詳細
パスに対応するマッピングがない、または server.context-path の外のパス 404 NoHandlerFoundException No endpoint GET /x.
パスはマッピングされているが、このメソッドではない 405、Allow 付き HttpRequestMethodNotSupportedException Method 'DELETE' is not supported.
consumes にない Content-Type、@RequestBody オブジェクトに対して JSON でない (または欠落した) もの、あるいはメディアタイプですらないもの 415、Accept 付き HttpMediaTypeNotSupportedException Content-Type 'text/xml' is not supported.
produces のどれも (オブジェクトなら JSON も) Accept に合わない 406 HttpMediaTypeNotAcceptableException Acceptable representations: [application/json].
必須の値がない 400 MissingRequestValueException Required parameter 'q' is not present. (header、cookie、path variable、part も)
変換できない値 400 MethodArgumentTypeMismatchException Failed to convert 'page' with value: 'two'
ボディがない、壊れている、形が違う、またはフォームの % エスケープが不正 400 HttpMessageNotReadableException Failed to read request
@Valid の違反 400、errors 付き MethodArgumentNotValidException Invalid request content.
headers の条件を満たさない 400 ResponseStatusException Unsatisfied header conditions
server.max-http-request-body-size を超えるリクエストボディ 413 PayloadTooLargeErrorException The request body exceeds 10485760 bytes.
spring.web.multipart.max-file-size または max-request-size を超える、あるいは max-part-count より多くのパートを持つアップロード 413 MaxUploadSizeExceededException Maximum upload size exceeded: ...
壊れたマルチパートリクエスト、またはマルチパートでないリクエストへの @RequestPart 400 MultipartRequestException Failed to parse multipart request: ...
server.connection-timeout (60 秒) の間何も送らないリクエストボディ 408 ResponseStatusException The request body did not arrive in time
リクエストの期限 (server.request-timeout) が過ぎた 503 AsyncRequestTimeoutException The request did not complete in time.
server.session.max-sessions を超える新しいセッション 503 TooManyActiveSessionsException Too many active sessions
ユーザーがいないのに null 非許容の Principal パラメーター 401 ResponseStatusException
throw ResponseStatusException(status, reason) そのステータス その理由
ErrorResponse または ErrorResponseException そのステータス、そのヘッダー付き その problem
HandlerExceptionResolver が応答するエラー そのステータス、そのヘッダー付き その problem
その他の例外 500 なし: クライアントには例外について何も伝わらない

バリデーションの応答は違反を列挙します。

{"type":"about:blank","title":"Bad Request","status":400,"detail":"Invalid request content.","instance":"/api/books",
 "errors":[{"field":"title","message":"must not be blank","rejectedValue":""}]}

各フィールドエラーは field、message、rejectedValue を持ちます。オブジェクト全体のエラーは object と message を持ちます。メッセージはアプリケーションの MessageSource から、なければ制約のデフォルトメッセージから取られます。

これらの例外はすべて ErrorResponseException であり、@ExceptionHandler で捕まえて別の形で応答できます (@ExceptionHandler を参照)。これらは package:spring_boot_starter_web/spring_boot_starter_web.dart からエクスポートされています。

フィルターより前に応答されるもの

サーバー自身が、フィルターやハンドラーに届く前に応答するリクエストがあります。

リクエスト ステータス
GET、HEAD、POST、PUT、PATCH、DELETE、OPTIONS、TRACE 以外のメソッド 501 Unsupported method
server.ssl.client-auth=need でクライアント証明書がない 403 A client certificate is required
Host がない、壊れている、または絶対形式のターゲットのホストと一致しない 400
パス中のエンコードされた /、\、NUL (%2F、%5C、%00) 400
マトリックスパラメーターの後ろの . または .. セグメント (/files/..;/secret) 400
パスまたはクエリ中の UTF-8 でない % エスケープ (/%FF) 400

これらの応答も problem です。

プレーンテキストの応答

Spring と同様に、二種類の応答は problem ではなくプレーンテキストです。

ロギング

エラーは spring.web.mvc でログに記録されます。

エラー レベル 行
500 未満の ErrorResponse (404、400 など) debug Resolved [NoHandlerFoundException: No endpoint GET /x.]
500 以上の ErrorResponse (ResponseStatusException(503)、拒否されたセッション) warning。スタックトレースなし。同じ型とステータスについて 10 秒に最大 1 回 Request GET /x answered with ResponseStatusException: 503 Down for maintenance。省略されたものがあれば (4 more of these not logged since the last warning) が付く (省略されたものは debug レベルで記録される)
その他の例外 (500) error。スタックトレース付き Request GET /x failed
レスポンスのコミット後のエラー warning。スタックトレース付き Request GET /x failed after the response was committed
例外を投げた @ExceptionHandler warning The @ExceptionHandler ApiErrors.notFound failed handling ...
応答した HandlerExceptionResolver (ステータスを問わない) debug Resolved [<the error>] as 409 by RoomTakenResolver
例外を投げた HandlerExceptionResolver warning The HandlerExceptionResolver RoomTakenResolver failed handling ...

ログ行のパスとテキストは安全な形に変換されます。改行は <EOL> に、制御文字は ? になります。logging.level.spring.web.servlet.DispatcherServlet=debug を指定すると、すべてのリクエストもログに記録されます (GET "/api/books", parameters={masked} と Completed 404 Not Found)。spring.mvc.log-request-details=true はパラメーターを、trace レベルではヘッダーも表示します。認証情報は常にマスクされます。

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;
  }
}

重要な違い:

関連項目