# 错误码与处理建议

REST 错误统一返回 JSON 对象 `error`，用 `code` 判断类型，不要依赖 `message` 文案。

> Source: https://tokenearly.com/developers/errors · Docs index: https://tokenearly.com/developers/llms.txt · OpenAPI: https://api.tokenearly.com/v1/openapi.json

## 格式

```json
{
  "error": {
    "code": "invalid_api_key",
    "message": "This API key does not exist or has been revoked.",
    "docs": "https://tokenearly.com/en/developers/errors"
  }
}
```

所有 REST 错误都是这个格式，包括路径不存在（404 `not_found`）、HTTP 方法不对（405 `method_not_allowed`）与服务端错误（5xx `internal_error`）。MCP 的响应保持 JSON-RPC 格式：协议层的问题（未知工具、参数不合规）是 JSON-RPC `error`，接口层的错误（Key、权限、限频等）是工具结果里的 `isError: true`，内容同样是 `{"error": {"code", "message"}}`。

## HTTP 错误

| code | HTTP | 含义与处理 |
|---|---|---|
| `missing_api_key` | 401 | 没有带 Key。用 Authorization: Bearer <Key>。 |
| `key_expired` | 401 | 试用 Key 已到期。重新申请试用 Key，或开通后创建正式 Key。 |
| `invalid_api_key` | 401 | Key 不存在，或已被重置 / 吊销。 |
| `plan_required` | 403 | 当前套餐不含开发者 API，或不含该项能力。 |
| `ip_not_allowed` | 403 | 这把 Key 设置了 IP 白名单，请求来源 IP 不在其中。 |
| `invalid_cursor` | 400 | after / before 不是合法的 ID（查事件时是事件 ID，查我的推送时是推送 ID），两者同时出现，或（仅查事件）updated_after 与 before 同时使用。 |
| `invalid_parameter` | 400 | 参数类型或取值不合法（例如 limit 超出范围）。 |
| `not_found` | 404 | 你的主题范围内没有这个事件（GET /v1/events/{id}），或请求的路径不存在（例如拼错了接口地址）。 |
| `method_not_allowed` | 405 | 路径存在，但不支持这个 HTTP 方法（例如对 /v1/events 发 POST）。REST 接口都是 GET，只有 MCP 用 POST；响应头 Allow 列出支持的方法。 |
| `rate_limited` | 429 | 超过这把 Key 的请求频率（REST 与 MCP 合计，间隔见 `/v1/me` 的 `limits.rest_interval_seconds`）；按 Retry-After 头等待后重试。 |
| `internal_error` | 500 | 服务端出错（5xx，格式同上）。用指数退避重试（1、2、4… 秒，设上限）。服务重启的短暂时间里也可能收到不带 JSON 正文的 502 / 503 / 504，按同样方式重试。 |

## 实时流错误

实时流先发一条 `op = "error"` 的消息，再以对应关闭码断开；只有 `invalid_message`（客户端消息不合规）不断开：

| code | 关闭码 | 含义与处理 |
|---|---|---|
| `missing_api_key` | 4001 | 没有带 Key。用 Authorization: Bearer <Key>。 |
| `key_expired` | 4001 | 试用 Key 已到期。重新申请试用 Key，或开通后创建正式 Key。 |
| `invalid_api_key` | 4001 | Key 不存在，或已被重置 / 吊销。 |
| `plan_required` | 4003 | 当前套餐不含开发者 API，或不含该项能力。 |
| `ip_not_allowed` | 4003 | 这把 Key 设置了 IP 白名单，请求来源 IP 不在其中。 |
| `invalid_cursor` | 4400 | 连接参数 after 不是合法的事件 ID；以 4400 关闭，改正后再连。 |
| `too_many_connections` | 4029 | 这把 Key 的实时连接名额已满（见 `/v1/me` 的 `limits.streams_per_key`），新连接被拒绝。先关闭旧连接，或给另一台机器用另一把 Key。 |
| `invalid_message` | 不断开 | WebSocket 客户端消息不合规：不是 JSON 对象、缺少字符串 op、op 未知，或 topics 为空 / 不是字符串列表。连接保持不断，改正后重发即可。 |
| `slow_consumer` | 4008 | 客户端处理太慢、积压过多；带 after 重连即可续上。 |

## 什么时候重试

- `429`：按 `Retry-After` 等待后重试。
- `5xx` 与网络错误：指数退避重试（1、2、4… 秒，设上限）。
- `401` / `403` / `400`：不要重试，先修正 Key、套餐或参数。
