跳转到主要内容

错误格式

所有错误均遵循统一的 JSON 格式:
{
  "error": {
    "message": "人类可读的错误描述",
    "type": "error_type"
  }
}

错误类型

HTTP 状态码错误类型描述
400invalid_request_error请求体格式错误或缺少必填字段
401authentication_errorAPI key 缺失、无效或已过期
402payment_required额度不足 — 请为账户充值
403permission_error / forbidden_error该密钥无权访问所请求的提供商或资源
413invalid_request_error请求体过大(最大 10 MB)
429rate_limit_error超出速率限制(RPM 或每日上限)
502server_error上游提供商请求失败
503server_error所请求的模型没有可用提供商

常见错误与解决方案

401 — API Key 无效

{
  "error": {
    "message": "invalid api key",
    "type": "authentication_error"
  }
}
解决方案: 检查您的 API key 是否正确且未被撤销。

403 — 提供商不被允许

{
  "error": {
    "message": "provider 'anthropic' is not allowed for this API key",
    "type": "forbidden_error"
  }
}
解决方案: 您的 API key 存在 allowed_providers 限制。请使用其他密钥,或通过管理 API 更新允许的提供商。

429 — 触发限流

{
  "error": {
    "message": "rate limit exceeded",
    "type": "rate_limit_error"
  }
}
解决方案: 实施指数退避策略。考虑提高该密钥的速率限制。

502 — 上游请求失败

{
  "error": {
    "message": "upstream request failed",
    "type": "server_error"
  }
}
解决方案: LLM 提供商返回错误或无法访问。ARouter 会自动处理密钥故障转移,但提供商本身可能正在经历问题。请重试或切换到其他提供商。

在代码中处理错误

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")

重试策略

对于生产应用,我们建议:
  1. 对 429 和 502 使用指数退避重试
  2. 不要重试 400、401、403 — 这些是永久性错误
  3. 设置最大重试次数(例如 3 次)
  4. 考虑多模型路由 — 如果某个模型无法处理请求,可通过 modelsroute 发送有序候选列表
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 事件在流体内容中传递。
流中途错误格式如下:
{
  "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",则表示流异常终止。
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);
}
完整的流式错误处理示例请参阅流式传输指南