Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Build LLM-powered apps with the Anthropic Claude API or SDK across Python, TypeScript, Java, Go, Ruby, C#, and PHP.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
shared/error-codes.md
1# HTTP Error Codes Reference23This file documents HTTP error codes returned by the Claude API, their common causes, and how to handle them. For language-specific error handling examples, see the `python/` or `typescript/` folders.45## Error Code Summary67| Code | Error Type | Retryable | Common Cause |8| ---- | ----------------------- | --------- | ------------------------------------ |9| 400 | `invalid_request_error` | No | Invalid request format or parameters |10| 401 | `authentication_error` | No | Invalid or missing API key |11| 403 | `permission_error` | No | API key lacks permission |12| 404 | `not_found_error` | No | Invalid endpoint or model ID |13| 413 | `request_too_large` | No | Request exceeds size limits |14| 429 | `rate_limit_error` | Yes | Too many requests |15| 500 | `api_error` | Yes | Anthropic service issue |16| 529 | `overloaded_error` | Yes | API is temporarily overloaded |1718## Detailed Error Information1920### 400 Bad Request2122**Causes:**2324- Malformed JSON in request body25- Missing required parameters (`model`, `max_tokens`, `messages`)26- Invalid parameter types (e.g., string where integer expected)27- Empty messages array28- Messages not alternating user/assistant2930**Example error:**3132```json33{34"type": "error",35"error": {36"type": "invalid_request_error",37"message": "messages: roles must alternate between \"user\" and \"assistant\""38},39"request_id": "req_011CSHoEeqs5C35K2UUqR7Fy"40}41```4243**Fix:** Validate request structure before sending. Check that:4445- `model` is a valid model ID46- `max_tokens` is a positive integer47- `messages` array is non-empty and alternates correctly4849---5051### 401 Unauthorized5253**Causes:**5455- Missing `x-api-key` header or `Authorization` header56- Invalid API key format57- Revoked or deleted API key58- OAuth bearer token sent via `x-api-key` instead of `Authorization: Bearer`59- Both `ANTHROPIC_API_KEY` and `ANTHROPIC_AUTH_TOKEN` set — the SDK sends both headers and the API rejects the request6061**Fix:** Set `ANTHROPIC_API_KEY`, or run `ant auth login` and leave the client constructor empty. For raw HTTP with an OAuth token, use `Authorization: Bearer <token>` (not `x-api-key:`).6263---6465### 403 Forbidden6667**Causes:**6869- API key doesn't have access to the requested model70- Organization-level restrictions71- Attempting to access beta features without beta access7273**Fix:** Check your API key permissions in the Console. You may need a different API key or to request access to specific features.7475---7677### 404 Not Found7879**Causes:**8081- Typo in model ID (e.g., `claude-sonnet-4.6` instead of `claude-sonnet-4-6`)82- Using deprecated model ID83- Invalid API endpoint8485**Fix:** Use exact model IDs from the models documentation. You can use aliases (e.g., `claude-opus-4-8`).8687---8889### 413 Request Too Large9091**Causes:**9293- Request body exceeds maximum size94- Too many tokens in input95- Image data too large9697**Fix:** Reduce input size — truncate conversation history, compress/resize images, or split large documents into chunks.9899---100101### 400 Validation Errors102103Some 400 errors are specifically related to parameter validation:104105- `max_tokens` exceeds model's limit106- Invalid `temperature` value (must be 0.0-1.0)107- `budget_tokens` >= `max_tokens` in extended thinking108- Invalid tool definition schema109110**Model-specific 400s on Fable 5 / Opus 4.8 / 4.7:**111112- `temperature`, `top_p`, `top_k` are removed — sending any of them returns 400. Delete the parameter; see `shared/model-migration.md` → Per-SDK Syntax Reference.113- `thinking: {type: "enabled", budget_tokens: N}` is removed — sending it returns 400. Use `thinking: {type: "adaptive"}` instead.114- **Fable 5 only:** an explicit `thinking: {type: "disabled"}` returns 400 (it is accepted on Opus 4.8/4.7). Omit the `thinking` param entirely instead.115- **Fable 5 only:** if the organization is set to zero data retention (ZDR) — or any retention below the required 30 days — then **all** Fable 5 requests return `400 invalid_request_error`, even with a perfectly valid payload. Check the org's retention configuration before debugging the request body.116117**Common mistake with extended thinking on older models (Opus 4.6 and earlier):**118119```120# Wrong: budget_tokens must be < max_tokens121thinking: budget_tokens=10000, max_tokens=1000 → Error!122123# Correct124thinking: budget_tokens=10000, max_tokens=16000125```126127---128129### 429 Rate Limited130131**Causes:**132133- Exceeded requests per minute (RPM)134- Exceeded tokens per minute (TPM)135- Exceeded tokens per day (TPD)136137**Headers to check:**138139- `retry-after`: Seconds to wait before retrying140- `x-ratelimit-limit-*`: Your limits141- `x-ratelimit-remaining-*`: Remaining quota142143**Fix:** The Anthropic SDKs automatically retry 429 and 5xx errors with exponential backoff (default: `max_retries=2`). For custom retry behavior, see the language-specific error handling examples.144145---146147### 500 Internal Server Error148149**Causes:**150151- Temporary Anthropic service issue152- Bug in API processing153154**Fix:** Retry with exponential backoff. If persistent, check [status.anthropic.com](https://status.anthropic.com).155156---157158### 529 Overloaded159160**Causes:**161162- High API demand163- Service capacity reached164165**Fix:** Retry with exponential backoff. Consider using a different model (Haiku is often less loaded), spreading requests over time, or implementing request queuing.166167---168169## Common Mistakes and Fixes170171| Mistake | Error | Fix |172| ------------------------------- | ---------------- | ------------------------------------------------------- |173| `temperature`/`top_p`/`top_k` on Fable 5 / Opus 4.8 / 4.7 | 400 | Remove the parameter (see `shared/model-migration.md`) |174| `budget_tokens` on Fable 5 / Opus 4.8 / 4.7 | 400 | Use `thinking: {type: "adaptive"}` |175| `thinking: {type: "disabled"}` on Fable 5 | 400 | Omit the `thinking` param entirely (accepted on Opus 4.8/4.7) |176| Org set to ZDR / retention below 30 days (Fable 5) | 400 on every request | Fix the org's data-retention configuration — the payload isn't the problem |177| `budget_tokens` >= `max_tokens` (older models) | 400 | Ensure `budget_tokens` < `max_tokens` |178| Typo in model ID | 404 | Use valid model ID like `claude-opus-4-8` |179| First message is `assistant` | 400 | First message must be `user` |180| Consecutive same-role messages | 400 | Alternate `user` and `assistant` |181| API key in code | 401 (leaked key) | Use environment variable |182| Custom retry needs | 429/5xx | SDK retries automatically; customize with `max_retries` |183184## Typed Exceptions in SDKs185186**Always use the SDK's typed exception classes** instead of checking error messages with string matching. Each HTTP error code maps to a specific exception class:187188| HTTP Code | TypeScript Class | Python Class |189| --------- | --------------------------------- | --------------------------------- |190| 400 | `Anthropic.BadRequestError` | `anthropic.BadRequestError` |191| 401 | `Anthropic.AuthenticationError` | `anthropic.AuthenticationError` |192| 403 | `Anthropic.PermissionDeniedError` | `anthropic.PermissionDeniedError` |193| 404 | `Anthropic.NotFoundError` | `anthropic.NotFoundError` |194| 413 | `Anthropic.RequestTooLargeError` | `anthropic.RequestTooLargeError` |195| 429 | `Anthropic.RateLimitError` | `anthropic.RateLimitError` |196| 500+ | `Anthropic.InternalServerError` | `anthropic.InternalServerError` |197| 529 | `Anthropic.OverloadedError` | `anthropic.OverloadedError` |198| Any | `Anthropic.APIError` | `anthropic.APIError` |199200```typescript201// ✅ Correct: use typed exceptions202try {203const response = await client.messages.create({...});204} catch (error) {205if (error instanceof Anthropic.RateLimitError) {206// Handle rate limiting207} else if (error instanceof Anthropic.APIError) {208console.error(`API error ${error.status}:`, error.message);209}210}211212// ❌ Wrong: don't check error messages with string matching213try {214const response = await client.messages.create({...});215} catch (error) {216const msg = error instanceof Error ? error.message : String(error);217if (msg.includes("429") || msg.includes("rate_limit")) { ... }218}219```220221All exception classes extend `Anthropic.APIError`, which has a `status` property. Use `instanceof` checks from most specific to least specific (e.g., check `RateLimitError` before `APIError`).222223### Error `.type` Field224225All `APIStatusError` subclasses now expose a `.type` property (Python: `.type`, TypeScript: `.type`, Java: `.errorType()`, Go: `.Type()`, Ruby: `.type`, PHP: `.type`) that returns the API error type string (e.g., `"invalid_request_error"`, `"authentication_error"`, `"rate_limit_error"`, `"overloaded_error"`). Use this for programmatic error classification when you need finer granularity than the HTTP status code — for example, distinguishing `"billing_error"` from `"permission_error"` (both map to 403).226227```python228except anthropic.APIStatusError as e:229if e.type == "rate_limit_error":230# handle rate limiting231elif e.type == "overloaded_error":232# handle overload233```234