错误处理
本指南详细说明 TopRouter API 可能返回的错误码及其解决方案。
错误响应格式
当 API 请求出错时,响应体包含以下结构:
json
{
"error": {
"message": "错误描述信息",
"type": "error_type",
"code": "error_code"
}
}HTTP 状态码
400 — 请求参数错误
原因:请求体格式不正确或缺少必需参数。
解决方案:
- 检查 JSON 格式是否正确
- 确认所有必需参数已提供
- 确认参数类型正确(如
messages必须是数组)
json
// ❌ 错误示例
{
"model": "openai/gpt-5.5",
"messages": "你好" // messages 应该是数组
}
// ✅ 正确示例
{
"model": "openai/gpt-5.5",
"messages": [{"role": "user", "content": "你好"}]
}401 — 认证失败
原因:API Key 无效、缺失或格式错误。
解决方案:
- 确认请求中包含
Authorizationheader - 确认格式为
Bearer your-api-key - 确认 API Key 未被删除或过期
- 检查是否有多余空格
bash
# ✅ 正确的认证格式
curl https://toprouter.cc/chat/completions \
-H "Authorization: Bearer sk-your-api-key" \
-H "Content-Type: application/json" \
-d '...'403 — 权限不足
原因:账户余额不足或权限受限。
解决方案:
- 检查账户余额,必要时 充值
- 确认 API Key 有权限访问请求的资源
404 — 资源不存在
原因:请求的端点或模型不存在。
解决方案:
- 检查 API 端点 URL 是否正确
- 确认模型名称拼写正确
- 查看 模型列表 获取正确的模型 ID
429 — 请求过于频繁
原因:超过速率限制。
解决方案:
- 降低请求频率
- 实现指数退避重试
- 详见 速率限制
500 — 服务器内部错误
原因:服务端处理异常。
解决方案:
- 等待几秒后重试
- 如果持续出现,请联系客服
503 — 服务暂时不可用
原因:上游模型服务暂时不可用。
解决方案:
- 稍后重试
- 尝试切换到其他可用模型
- 关注社区获取服务状态更新
重试策略
指数退避
推荐使用指数退避策略处理可重试错误(429、500、503):
python
import time
import requests
def make_request_with_retry(url, headers, payload, max_retries=5):
for attempt in range(max_retries):
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200:
return response.json()
if response.status_code in [429, 500, 503]:
wait_time = min(2 ** attempt, 60) # 最长等待 60 秒
print(f"请求失败 ({response.status_code}),{wait_time} 秒后重试...")
time.sleep(wait_time)
continue
# 不可重试的错误
response.raise_for_status()
raise Exception("达到最大重试次数")TypeScript 版本
typescript
async function makeRequestWithRetry(
url: string,
headers: Record<string, string>,
payload: object,
maxRetries = 5
): Promise<any> {
for (let attempt = 0; attempt < maxRetries; attempt++) {
const response = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(payload),
});
if (response.ok) {
return response.json();
}
if ([429, 500, 503].includes(response.status)) {
const waitTime = Math.min(2 ** attempt, 60);
console.log(`请求失败 (${response.status}),${waitTime} 秒后重试...`);
await new Promise(resolve => setTimeout(resolve, waitTime * 1000));
continue;
}
throw new Error(`请求失败: ${response.status} ${response.statusText}`);
}
throw new Error('达到最大重试次数');
}调试技巧
启用详细日志
python
import openai
import logging
# 启用 HTTP 请求日志
logging.basicConfig(level=logging.DEBUG)
client = openai.OpenAI(
base_url="https://toprouter.cc",
api_key="your-api-key"
)检查请求和响应
使用 cURL 的 -v 参数查看详细请求信息:
bash
curl -v https://toprouter.cc/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-api-key" \
-d '{"model": "openai/gpt-5.5", "messages": [{"role": "user", "content": "test"}]}'💡 获取帮助
如果您无法解决遇到的错误,请通过以下渠道联系我们,并附上错误信息和请求详情:
- Telegram:t.me/+usySmwAIO-I3YjBl
- Discord:discord.gg/URHXXkVJ6y
