
# ProblemDetail

`ProblemDetail` は、RFC 9457 の標準形式 (`application/problem+json`) によるエラーレスポンスのボディです。ステータス、タイプ、タイトル、詳細、インスタンス、そして任意の追加フィールドを持ちます。`ErrorResponse`、`ErrorResponseException`、`ResponseStatusException` は、これを持つエラーです。

## 使う理由

API のすべてのエラーに同じ形を与えるので、クライアントは同じコードですべてを読めます。スターターは自身のエラー (パラメーターの欠落、不正なボディ、未知のパス) をこの形で応答します。アプリケーション自身のエラーにも同じ形で応答するには、コントローラーや `@ExceptionHandler` から `ProblemDetail` を返すか、これを持つ例外を投げます。

## 例

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

// 常に同じ応答を持つアプリケーションのエラー。
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 {
  // ステータスとメッセージ: 最も手軽な方法。
  @GetMapping('/{id}')
  String find(@PathVariable() int id) =>
      throw ResponseStatusException(HttpStatus.notFound, 'No order $id');

  // アプリケーション独自のタイプの problem。
  @PostMapping('/{isbn}')
  String order(@PathVariable() String isbn) => throw OutOfStockException(isbn);

  // リクエストが多すぎる: Retry-After ヘッダー付きの 429。
  @PostMapping('/bulk')
  String bulk() => throw ErrorResponseException(
    HttpStatus.tooManyRequests,
    headers: HttpHeaders()..set(HttpHeaders.retryAfterHeader, '30'),
    body: ProblemDetail.forStatusAndDetail(
      HttpStatus.tooManyRequests,
      'Try again in 30 seconds',
    ),
  );

  // 投げずに返す ProblemDetail。
  @GetMapping('/{id}/invoice')
  ProblemDetail invoice(@PathVariable() int id) =>
      ProblemDetail.forStatusAndDetail(HttpStatus.notFound, 'No invoice yet');
}
```

```text
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

### コンストラクター

| コンストラクター | 作るもの |
|---|---|
| `ProblemDetail(status, {type, title, detail, instance, properties})` | 標準メンバーを任意に持つ problem。`type` のデフォルトは `about:blank` |
| `ProblemDetail.forStatus(status)` | ステータスだけの problem。タイトルはステータスの理由句 |
| `ProblemDetail.forStatusAndDetail(status, detail)` | ステータスと詳細を持つ problem。最もよく使う方法 |
| `ProblemDetail.fromJson(json)` | デコード済みの JSON (クライアントが受け取ったエラーのボディなど) から読んだ problem。五つの標準メンバー以外は `properties` に入る。`status` がなければ 500 として読む。 |

### フィールド

| 名前 | 型 | デフォルト | 意味 |
|---|---|---|---|
| `status` | `int` | 必須 | HTTP ステータスコード。サーバーが problem を書き出すとき、レスポンスはこのステータスになる。 |
| `type` | `Uri` | `ProblemDetail.blankType` (`about:blank`) | problem の種類を表す URI。タイプで problem を区別するクライアント向け。`about:blank` はステータスですべてを表すことを意味する。 |
| `title` | `String?` | `null` | problem の種類の短い要約。`null` の場合、JSON にはステータスの理由句 (`Not Found`) が入る。 |
| `detail` | `String?` | `null` | この発生についてのクライアント向けの説明: `No book 978-0`。 |
| `instance` | `Uri?` | `null` | この発生を表す URI。`null` の場合、サーバーがリクエストのパスを設定する。 |
| `properties` | `Map<String, Object?>` | `{}` | 標準メンバーの後に書かれる追加メンバー。たとえば失敗したバリデーションの `errors`。 |

### メンバー

| メンバー | 動作 |
|---|---|
| `setProperty(name, value)` | 追加メンバーを加える。以前の値は置き換える |
| `effectiveTitle` | `title`。`null` の場合はステータスの理由句 (未知のステータスの場合だけ `null`) |
| `toJson()` | JSON オブジェクト: `type`、有効な `title`、`status`、`detail`、`instance` (`null` は省く)、その後に `properties` |
| `ProblemDetail.blankType` | `about:blank` |

ルール:

- **JSON。** メンバーは `type`、`title`、`status`、`detail`、`instance`、プロパティの順に書かれます。標準の名前 (`detail`) を持つプロパティはそのメンバーを置き換えます。`properties` の値は `jsonEncode` で書かれるので、JSON の値 (文字列、数値、真偽値、リスト、マップ) を使ってください。
- **メディアタイプ** は `application/problem+json` で、problem の `status` がレスポンスのステータスになります。`ResponseEntity` の中の `ProblemDetail` はエンティティのステータスになり、エンティティが設定した `Content-Type` を保ちます。
- メソッドの **`@ResponseStatus`** は、返された `ProblemDetail` のステータスを置き換えます。
- **詳細はクライアント向けにしてください。** そのまま送られます。例外のメッセージには SQL、ファイル名、値が含まれているかもしれません。よく考えずに詳細へコピーしないでください。

## ErrorResponse

`ErrorResponse` は、自身の HTTP 応答を持つエラーのインターフェースです。コントローラーがこれを投げると、サーバーは 500 の代わりにそれで応答します。

| メンバー | 型 | 意味 |
|---|---|---|
| `statusCode` | `int` | 応答のステータス。 |
| `headers` | `HttpHeaders` | 追加するヘッダー。誤ったメソッドの `Allow`、ログインがない場合の `WWW-Authenticate` など。同じ名前のヘッダーを置き換えるが、`Vary` だけは名前が追加される。 |
| `body` | `ProblemDetail` | ボディとして書かれる problem。ステータスは `statusCode` に設定される。 |

スターターのエラーはすべてこれです ([エラー](index.md) を参照)。`HandlerExceptionResolver` Bean はこれを返します ([HandlerExceptionResolver](handler-exception-resolver.md) を参照)。ほとんどのアプリケーションは、このインターフェースを実装するより、`ResponseStatusException` を投げるか `ErrorResponseException` を継承します。

## ErrorResponseException

`ErrorResponse` である例外で、スターター自身のエラーの基底クラスです。ヘッダーや problem の追加メンバーなど、ステータスとメッセージ以上のものが応答に必要なときに投げます。常に同じ応答を持つアプリケーションのエラーには、これを継承します。

| 名前 | 型 | デフォルト | 意味 |
|---|---|---|---|
| `statusCode` (位置引数) | `int` | 必須 | 応答のステータス。 |
| `body` | `ProblemDetail?` | ステータスだけの problem | 応答の problem。 |
| `headers` | `HttpHeaders?` | ヘッダーなし | 応答に追加するヘッダー。 |
| `cause` | `Object?` | `null` | このエラーの原因になったエラー。クライアントに送られることはない。 |

`toString()` は、ログに表示されるとおり `ClassName: status detail` です。

## ResponseStatusException

コントローラーやそこから呼ばれるコードから、エラーでリクエストを終える最も手軽な方法です。サーバーは、そのステータスと、理由を詳細とする problem で応答します。

| 名前 | 型 | デフォルト | 意味 |
|---|---|---|---|
| `statusCode` (位置引数) | `int` | 必須 | 応答のステータス。 |
| `reason` (位置引数) | `String?` | `null` | problem の `detail`。`null` の場合は詳細なし。 |
| `cause` (位置引数) | `Object?` | `null` | このエラーの原因になったエラー。送られない。 |

```dart
@GetMapping('/books/{isbn}')
Future<Book> find(@PathVariable() String isbn) async =>
    await books.findOrNull(isbn) ??
    (throw ResponseStatusException(HttpStatus.notFound, 'No book $isbn'));
```

500 以上の `ResponseStatusException` (メンテナンス中の 503 など) は、型とステータスごとに 10 秒に最大 1 回、スタックトレースなしの警告としてログに記録されます。500 未満は debug レベルです。

## クライアント側

Feign クライアント (またはエラーの応答を読むコード) は、`ProblemDetail.fromJson(jsonDecode(body))` でボディを problem に戻せます。追加メンバーは `properties` に入ります。

## Spring (Java) との対応

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

重要な違い:

- フィールドはセッターではなく通常の Dart のフィールドです (`problem.type = ...`)。`properties` は変更可能なマップです。
- 受け取った problem は `ProblemDetail.fromJson` で読みます。Spring ではそれに Jackson を使います。
- ステータスは `HttpStatusCode` オブジェクトではなく `int` です (`HttpStatus` の定数も `int` です)。

## 関連項目

- [エラー](index.md)
- [@ExceptionHandler](exception-handler.md)
- [戻り値](../controllers/results.md)
