> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.joytokens.ai/llms.txt.

# 错误

> JoyToken API 错误响应和处理方式

模型调用失败时，错误结构取决于所选协议：

#### OpenAI

```json
{
  "error": {
    "message": "missing api key",
    "type": "missing_api_key"
  }
}
```

#### Anthropic

```json
{
  "type": "error",
  "error": {
    "type": "invalid_request_error",
    "message": "invalid request"
  }
}
```

## 状态码

| HTTP 状态码      | `error.type`            | 原因                          | 处理方式                  |
| ------------- | ----------------------- | --------------------------- | --------------------- |
| `400`         | `invalid_request_error` | 请求体错误、`messages` 为空、body 过大 | 修正请求，不重试              |
| `401`         | `missing_api_key`       | 没有 API Key                  | 补充所选协议对应的 API Key 请求头 |
| `403`         | `invalid_api_key`       | Key 无效或不是 `ACTIVE`          | 换有效 Key               |
| `403`         | `policy_rejected`       | IP、模型、tier 或策略不允许           | 调整 Key 策略             |
| `402`         | `insufficient_quota`    | 额度或钱包余额不足                   | 充值或调整预算               |
| `502`         | `routing_error`         | 没有可用模型或路由失败                 | 短退避重试                 |
| `502`         | `upstream_error`        | 上游模型失败                      | 短退避重试                 |
| `503` / `504` | `upstream_error`        | 依赖服务暂时不可用或超时                | 指数退避重试                |

## 排障字段

| 字段                             | 来源    |
| ------------------------------ | ----- |
| `X-Request-ID`                 | 请求头   |
| `model` / `tier`               | 请求体   |
| HTTP 状态码                       | 响应状态  |
| `error.type` / `error.message` | 错误响应体 |

## 重试判断

```ts
export function shouldRetryJoyTokenError(status: number, type?: string) {
  if (status === 503 || status === 504) return true;
  if (status === 502 && (type === "routing_error" || type === "upstream_error")) return true;
  return false;
}
```

不要对 `400`、`401`、`402`、`403` 做无限重试。先修正请求、认证、预算或策略。