跳轉到主要內容

錯誤格式

所有錯誤均遵循統一的 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);
}
完整的串流錯誤處理範例請參閱串流傳輸指南