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

# Errors

> JoyToken API error responses and handling

Model-call failures use the error envelope of the selected protocol:

#### OpenAI

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

#### Anthropic

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

## Status Codes

| HTTP status   | `error.type`            | Cause                                             | Fix                               |
| ------------- | ----------------------- | ------------------------------------------------- | --------------------------------- |
| `400`         | `invalid_request_error` | Invalid body, empty `messages`, or oversized body | Fix request; do not retry         |
| `401`         | `missing_api_key`       | No API key                                        | Add the protocol's API key header |
| `403`         | `invalid_api_key`       | Key is invalid or not `ACTIVE`                    | Use a valid key                   |
| `403`         | `policy_rejected`       | IP, model, tier, or policy is not allowed         | Adjust key policy                 |
| `402`         | `insufficient_quota`    | Quota or wallet balance is insufficient           | Top up or adjust budget           |
| `502`         | `routing_error`         | No usable model or routing failed                 | Short backoff retry               |
| `502`         | `upstream_error`        | Upstream model failed                             | Short backoff retry               |
| `503` / `504` | `upstream_error`        | Dependency unavailable or timed out               | Exponential backoff retry         |

## Debug Fields

| Field                          | Source              |
| ------------------------------ | ------------------- |
| `X-Request-ID`                 | Request header      |
| `model` / `tier`               | Request body        |
| HTTP status                    | Response status     |
| `error.type` / `error.message` | Error response body |

## Retry Check

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

Do not infinitely retry `400`, `401`, `402`, or `403`. Fix the request, auth, budget, or policy first.