#错误处理
本文档说明 API 的错误响应格式和常见错误码。
#错误响应格式
所有错误响应都遵循统一的 JSON 格式:
json{
"statusCode": 400,
"message": "错误描述",
"error": "Bad Request"
}
对于验证错误,可能包含更详细的字段信息:
json{
"statusCode": 400,
"message": ["name must be a string", "model is required"],
"error": "Bad Request"
}
#HTTP 状态码
| 状态码 | 说明 |
|---|---|
200 | 请求成功 |
201 | 资源创建成功 |
202 | 请求已接受(异步处理) |
204 | 操作成功,无返回内容 |
400 | 请求参数错误 |
401 | 未认证(缺少或无效的 API Key) |
403 | 权限不足 |
404 | 资源未找到 |
409 | 资源冲突 |
429 | 请求频率超限 |
500 | 服务器内部错误 |
#常见错误场景
#401 Unauthorized
原因: API Key 缺失或无效
bash# 缺少 API Key
curl -X GET "https://your-domain.com/v1/agents"
# 返回
# HTTP 401
# {"statusCode":401,"message":"Unauthorized"}
解决方案: 确保在请求头中正确传入 X-API-Key。
#400 Bad Request - Project context required
原因: 创建 Agent 时缺少 Project 上下文
json{
"statusCode": 400,
"message": "Project context is required to create an agent. Ensure your account has a default project.",
"error": "Bad Request"
}
解决方案: 确保 API Key 已关联 Project,或通过 X-Project-Id 请求头指定。
#403 Forbidden
原因: API Key 的权限不足以执行该操作
json{
"statusCode": 403,
"message": "Forbidden resource",
"error": "Forbidden"
}
解决方案: 检查 API Key 的权限级别(read/write/admin)。
#404 Not Found
原因: 请求的资源不存在或不属于当前组织
json{
"statusCode": 404,
"message": "Agent agent_xxx not found",
"error": "Not Found"
}
#429 Too Many Requests
原因: 请求频率超过限制
json{
"statusCode": 429,
"message": "Too many requests",
"error": "Too Many Requests"
}
解决方案: 降低请求频率,实现指数退避重试。详见下方速率限制章节。
#速率限制
API 请求受到基于订阅计划的频率限制,分为三个层级:
#计划限制
| 计划 | 每分钟 | 每小时 | 每天 |
|---|---|---|---|
| Free | 60 | 1,000 | 10,000 |
| Pro | 600 | 10,000 | 100,000 |
| Team | 3,000 | 50,000 | 500,000 |
| Enterprise | 10,000 | 200,000 | 2,000,000 |
#限流层级
| 层级 | 范围 | 窗口 | 说明 |
|---|---|---|---|
| Level 1 | API Key | 1 分钟 | 每个 API Key 的请求频率限制 |
| Level 2 | 组织 | 1 小时 | 组织级别的小时请求总量 |
| Level 3 | 组织 | 24 小时 | 组织级别的日请求总量 |
#响应头
每个 API 响应都包含以下速率限制相关的响应头:
| 响应头 | 说明 |
|---|---|
X-RateLimit-Limit | 当前窗口的请求上限 |
X-RateLimit-Remaining | 当前窗口剩余请求数 |
X-RateLimit-Reset | 窗口重置的 Unix 时间戳 |
Retry-After | 触发限流时,建议等待的秒数 |
#限流错误响应
json{
"error": {
"code": "RATE_LIMIT_EXCEEDED",
"message": "Rate limit exceeded. Please retry after 45 seconds.",
"retryAfter": 45
}
}
#最佳实践
#重试策略
对于 429 和 5xx 错误,建议实现指数退避重试:
javascriptasync function fetchWithRetry(url, options, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const response = await fetch(url, options);
if (response.status === 429 || response.status >= 500) {
const retryAfter = response.headers.get('Retry-After');
const delay = retryAfter
? parseInt(retryAfter) * 1000
: Math.pow(2, i) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
return response;
} catch (error) {
if (i === maxRetries - 1) throw error;
const delay = Math.pow(2, i) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
#错误日志
建议记录以下信息用于调试:
- 请求的 URL 和方法
- HTTP 状态码
- 错误响应体
- 请求时间戳
- 请求 ID(如果响应头中包含)
#SSE 流式错误处理
在流式对话中,错误会通过 SSE 事件传递:
data: {"error":"Tool execution failed: timeout","sessionId":"sess_xxx"}
data: [DONE]
建议在客户端监听 error 字段并适当处理。