> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentwallex.com/llms.txt
> Use this file to discover all available pages before exploring further.

# エラーハンドリング

> エラーフォーマット、エラータイプ、SDKおよびREST APIでのエラー処理方法。

## エラーフォーマット

すべてのAgentWallex APIエラーは一貫したJSON形式に従います：

```json theme={null}
{
  "code": "invalid_request",
  "type": "invalid_request_error",
  "message": "human readable error description"
}
```

| フィールド     | 説明                                                    |
| --------- | ----------------------------------------------------- |
| `code`    | 機械可読エラーコード（例：`policy_violation`、`insufficient_funds`） |
| `type`    | エラーカテゴリ（下表参照）                                         |
| `message` | 何が問題だったかの人間が読める説明                                     |

## エラータイプ

| タイプ                     | HTTPステータス | 説明                                |
| ----------------------- | --------- | --------------------------------- |
| `invalid_request_error` | 400       | リクエストボディまたはパラメータが無効です             |
| `authentication_error`  | 401       | APIキー/トークンが不足または無効です              |
| `authorization_error`   | 403       | 有効な資格情報ですが権限が不足しています              |
| `not_found_error`       | 404       | リクエストされたリソースが存在しません               |
| `rate_limit_error`      | 429       | リクエストが多すぎます — 指定された遅延後にリトライしてください |
| `internal_error`        | 500       | サーバーサイドエラー — 持続する場合はサポートに連絡してください |

## 一般的なエラーコード

| コード                   | タイプ                     | 説明                                     |
| --------------------- | ----------------------- | -------------------------------------- |
| `policy_violation`    | `invalid_request_error` | トランザクションがポリシーエンジンによってブロックされました         |
| `insufficient_funds`  | `invalid_request_error` | ウォレット残高がトランザクションに対して不足しています            |
| `agent_frozen`        | `invalid_request_error` | エージェントが凍結されています — トランザクション前に凍結解除してください |
| `invalid_chain`       | `invalid_request_error` | サポートされていないまたは無効なチェーンIDです               |
| `invalid_token`       | `invalid_request_error` | 指定されたチェーンでサポートされていないトークンです             |
| `invalid_address`     | `invalid_request_error` | 受取人アドレスの形式が不正です                        |
| `session_expired`     | `invalid_request_error` | x402セッションの有効期限が切れたか予算を超過しました           |
| `rate_limit_exceeded` | `rate_limit_error`      | APIレート制限に達しました                         |
| `approval_timeout`    | `invalid_request_error` | タイムアウト内に人間承認が得られませんでした                 |

## SDKエラーハンドリング

### TypeScript

TypeScript SDKは特定のエラータイプに対する型付きエラークラスを提供します：

```typescript theme={null}
import {
  AgentWallexError,
  PolicyViolationError,
} from "@agentwallex/sdk";

try {
  const tx = await aw.payments.send({
    agentId: "agent_abc123",
    to: "0xRecipientAddress",
    amount: "50.00",
    token: "USDC",
  });
} catch (error) {
  if (error instanceof PolicyViolationError) {
    console.log(`Policy violated: ${error.rule}`);
    console.log(`Details: ${error.message}`);
    // Handle: adjust amount, use different address, etc.
  } else if (error instanceof AgentWallexError) {
    console.log(`API error [${error.code}]: ${error.message}`);

    switch (error.code) {
      case "insufficient_funds":
        // Top up the wallet
        break;
      case "agent_frozen":
        // Unfreeze or use a different agent
        break;
      case "rate_limit_exceeded":
        // Wait and retry
        break;
      default:
        // Log and alert
        break;
    }
  } else {
    // Network error or unexpected exception
    console.error("Unexpected error:", error);
  }
}
```

### Python

```python theme={null}
from agentwallex import AgentWallexError, PolicyViolationError

try:
    tx = await aw.payments.send(
        agent_id="agent_abc123",
        to="0xRecipientAddress",
        amount="50.00",
        token="USDC",
    )
except PolicyViolationError as e:
    print(f"Policy violated: {e.rule}")
    print(f"Details: {e.message}")
except AgentWallexError as e:
    print(f"API error [{e.code}]: {e.message}")
except Exception as e:
    print(f"Unexpected error: {e}")
```

## リトライ戦略

<Tip>
  リトライには指数バックオフを使用してください。`rate_limit_error`と`internal_error`のみリトライしてください。`invalid_request_error`や`authentication_error`はリトライせず、リクエストの修正が必要です。
</Tip>

```typescript theme={null}
async function withRetry<T>(
  fn: () => Promise<T>,
  maxRetries: number = 3
): Promise<T> {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (error) {
      if (
        error instanceof AgentWallexError &&
        (error.type === "rate_limit_error" || error.type === "internal_error") &&
        attempt < maxRetries
      ) {
        const delay = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s
        await new Promise(resolve => setTimeout(resolve, delay));
        continue;
      }
      throw error;
    }
  }
  throw new Error("Max retries exceeded");
}

// Usage
const tx = await withRetry(() =>
  aw.payments.send({
    agentId: "agent_abc123",
    to: "0xRecipientAddress",
    amount: "50.00",
    token: "USDC",
  })
);
```

## HTTPステータスコードリファレンス

| ステータス | 意味       | アクション                           |
| ----- | -------- | ------------------------------- |
| 200   | 成功       | レスポンスを処理します                     |
| 201   | 作成完了     | リソースが正常に作成されました                 |
| 400   | 不正なリクエスト | リクエストパラメータを修正してください             |
| 401   | 未認証      | APIキーを確認してください                  |
| 403   | 禁止       | 権限/プランティアを確認してください              |
| 404   | 未検出      | リソースIDが存在するか確認してください            |
| 429   | レート制限    | バックオフで待機してリトライしてください            |
| 500   | サーバーエラー  | バックオフでリトライ、持続する場合はサポートに連絡してください |
