跳转到主内容

错误处理

Creatoria Agent API 文档

#错误处理

本文档说明 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 请求受到基于订阅计划的频率限制,分为三个层级:

#计划限制

计划每分钟每小时每天
Free601,00010,000
Pro60010,000100,000
Team3,00050,000500,000
Enterprise10,000200,0002,000,000

#限流层级

层级范围窗口说明
Level 1API Key1 分钟每个 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
  }
}

#最佳实践

#重试策略

对于 4295xx 错误,建议实现指数退避重试:

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));
    }
  }
}

#错误日志

建议记录以下信息用于调试:

  1. 请求的 URL 和方法
  2. HTTP 状态码
  3. 错误响应体
  4. 请求时间戳
  5. 请求 ID(如果响应头中包含)

#SSE 流式错误处理

在流式对话中,错误会通过 SSE 事件传递:

data: {"error":"Tool execution failed: timeout","sessionId":"sess_xxx"}

data: [DONE]

建议在客户端监听 error 字段并适当处理。