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

# 錯誤處理

> 了解 ARouter 的錯誤回應格式，以及如何在應用程式中進行處理。

## 錯誤格式

所有錯誤均遵循統一的 JSON 格式：

```json theme={null}
{
  "error": {
    "message": "人類可讀的錯誤描述",
    "type": "error_type"
  }
}
```

## 錯誤類型

| HTTP 狀態碼 | 錯誤類型                                   | 描述                |
| -------- | -------------------------------------- | ----------------- |
| `400`    | `invalid_request_error`                | 請求體格式錯誤或缺少必填欄位    |
| `401`    | `authentication_error`                 | API key 缺失、無效或已過期 |
| `402`    | `payment_required`                     | 額度不足 — 請為帳戶儲值     |
| `403`    | `permission_error` / `forbidden_error` | 該金鑰無權存取所請求的提供商或資源 |
| `413`    | `invalid_request_error`                | 請求體過大（最大 10 MB）   |
| `429`    | `rate_limit_error`                     | 超出速率限制（RPM 或每日上限） |
| `502`    | `server_error`                         | 上游提供商請求失敗         |
| `503`    | `server_error`                         | 所請求的模型沒有可用提供商     |

## 常見錯誤與解決方案

### 401 — API Key 無效

```json theme={null}
{
  "error": {
    "message": "invalid api key",
    "type": "authentication_error"
  }
}
```

**解決方案：** 檢查您的 API key 是否正確且未被撤銷。

### 403 — 提供商不被允許

```json theme={null}
{
  "error": {
    "message": "provider 'anthropic' is not allowed for this API key",
    "type": "forbidden_error"
  }
}
```

**解決方案：** 您的 API key 存在 `allowed_providers` 限制。請使用其他金鑰，或透過管理 API 更新允許的提供商。

### 429 — 觸發限流

```json theme={null}
{
  "error": {
    "message": "rate limit exceeded",
    "type": "rate_limit_error"
  }
}
```

**解決方案：** 實作指數退避策略。考慮提高該金鑰的速率限制。

### 502 — 上游請求失敗

```json theme={null}
{
  "error": {
    "message": "upstream request failed",
    "type": "server_error"
  }
}
```

**解決方案：** LLM 提供商回傳錯誤或無法存取。ARouter 會自動處理金鑰故障轉移，但提供商本身可能正在遭遇問題。請重試或切換至其他提供商。

## 在程式碼中處理錯誤

<Tabs>
  <Tab title="Python (OpenAI)">
    ```python theme={null}
    from openai import OpenAI, APIStatusError, APIConnectionError

    client = OpenAI(
        base_url="https://api.arouter.ai/v1",
        api_key="lr_live_xxxx",
    )

    try:
        response = client.chat.completions.create(
            model="openai/gpt-5.4",
            messages=[{"role": "user", "content": "Hello!"}],
        )
    except APIStatusError as e:
        if e.status_code == 401:
            print("Invalid API key")
        elif e.status_code == 402:
            print("Insufficient credits — top up your account")
        elif e.status_code == 429:
            print("Rate limited, backing off...")
        elif e.status_code in (502, 503):
            print("Provider error, retrying...")
        else:
            print(f"API error {e.status_code}: {e.message}")
    except APIConnectionError:
        print("Network error — check your connection")
    ```
  </Tab>

  <Tab title="Node.js (OpenAI)">
    ```typescript theme={null}
    import OpenAI from "openai";

    const client = new OpenAI({
      baseURL: "https://api.arouter.ai/v1",
      apiKey: "lr_live_xxxx",
    });

    try {
      const response = await client.chat.completions.create({
        model: "openai/gpt-5.4",
        messages: [{ role: "user", content: "Hello!" }],
      });
    } catch (error) {
      if (error instanceof OpenAI.APIError) {
        switch (error.status) {
          case 401: console.error("Invalid API key"); break;
          case 402: console.error("Insufficient credits"); break;
          case 429: console.error("Rate limited"); break;
          case 502:
          case 503: console.error("Provider error"); break;
          default:  console.error(`Error ${error.status}: ${error.message}`);
        }
      }
    }
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    resp, err := client.ChatCompletion(ctx, req)
    if err != nil {
        var apiErr *arouter.APIError
        if errors.As(err, &apiErr) {
            switch apiErr.StatusCode {
            case 401:
                log.Fatal("Invalid API key")
            case 429:
                log.Println("Rate limited, backing off...")
                time.Sleep(time.Second)
            case 502:
                log.Println("Provider error, retrying...")
            }
        } else {
            log.Fatal("Network error:", err)
        }
    }
    ```
  </Tab>
</Tabs>

## 重試策略

對於正式應用，我們建議：

1. **對 429 和 502 使用指數退避重試**
2. **不要重試 400、401、403** — 這些是永久性錯誤
3. **設定最大重試次數**（例如 3 次）
4. **考慮多模型路由** — 如果某個模型無法處理請求，可透過 `models` 和 `route` 傳送有序候選清單

```python theme={null}
import time
from openai import OpenAI, APIStatusError

def call_with_retry(client, request, max_retries=3):
    for attempt in range(max_retries):
        try:
            return client.chat.completions.create(**request)
        except APIStatusError as e:
            if e.status_code in (429, 502, 503) and attempt < max_retries - 1:
                time.sleep(2 ** attempt)
                continue
            raise
```

## 串流傳輸中的錯誤處理

當使用串流傳輸（`stream: true`）時，錯誤的行為因發生時機而有所不同：

* **在傳送任何 Token 之前** — ARouter 回傳帶有非 200 狀態碼的標準 HTTP 錯誤回應，處理方式與非串流錯誤相同。
* **在 Token 已傳送之後** — HTTP 狀態已經是 200 OK，錯誤將作為 SSE 事件在串流內容中傳遞。

串流途中錯誤格式如下：

```json theme={null}
{
  "id": "chatcmpl-xxx",
  "object": "chat.completion.chunk",
  "error": {
    "code": "server_error",
    "message": "Provider disconnected unexpectedly"
  },
  "choices": [
    { "index": 0, "delta": { "content": "" }, "finish_reason": "error" }
  ]
}
```

請檢查每個資料區塊的 `finish_reason`。如果值為 `"error"`，則表示串流異常終止。

```typescript theme={null}
for await (const chunk of stream) {
  // Check for mid-stream error
  if ("error" in chunk) {
    console.error(`Stream error: ${(chunk as any).error.message}`);
    break;
  }
  if (chunk.choices[0]?.finish_reason === "error") {
    console.error("Stream terminated due to an error");
    break;
  }
  const content = chunk.choices[0]?.delta?.content;
  if (content) process.stdout.write(content);
}
```

完整的串流錯誤處理範例請參閱[串流傳輸指南](/zh-Hant/guides/streaming)。
