> ## 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/guides/streaming)。
