> ## 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` | 不支援或無效的 chain 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 | 伺服器錯誤 | 使用退避策略重試；若持續發生請聯繫支援 |
