# 30.4 Errors by class: retry, fall back or fix (/building-ai-workers/shipping-claude-applications/errors-by-class)

---
type: Document
title: "30.4 Errors by class: retry, fall back or fix"
description: "What the SDK has already retried, the one move for each error class, which faults a fallback suits, which models each environment may end on, and how a stream ends right."
status: stable
order: 330.04
ksor:
  owner: team:panaversity
  audience:
    - public
  approval:
    by: process:panaversity
    at: 2026-11-30T10:58:03Z
chapter: '30'
part: III
expert_status: builder-only
concepts: [ "30.4" ]
last_verified: '2026-11-30'

sources:
  - id: anthropic-errors
    title: Errors (Claude API docs, verified 2026-11-30)
    resource: https://platform.claude.com/docs/en/api/errors
  - id: anthropic-model-ids
    title: Model IDs and versions (Claude API docs, verified 2026-11-30)
    resource: https://platform.claude.com/docs/en/about-claude/models/model-ids-and-versions
  - id: anthropic-python-sdk
    title: Python SDK (Claude API docs, verified 2026-11-30)
    resource: https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/python
  - id: anthropic-rate-limits
    title: Rate limits (Claude API docs, verified 2026-11-30)
    resource: https://platform.claude.com/docs/en/api/rate-limits
  - id: anthropic-refusals-and-fallback
    title: Refusals and fallback (Claude API docs, verified 2026-11-30)
    resource: https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback
  - id: anthropic-streaming
    title: Streaming messages (Claude API docs, verified 2026-11-30)
    resource: https://platform.claude.com/docs/en/build-with-claude/streaming
  - id: anthropic-typescript-sdk
    title: TypeScript SDK (Claude API docs, verified 2026-11-30)
    resource: https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/typescript
generated:
  at: 2026-11-30T10:58:03Z
  by: esl-rewrite/1.2.0+ksor.1
trust_tier: unverified
build_id: sha256:d6ce3f28a2cf8e492a60bae1b426b7cc6466e35e83d70c3b9763db2c55009f4b
dirty: true
ksor_version: 0.0.60
---

**In everyday life.** A shop sends a parcel by courier, and it comes back with a note. The note decides what happens next. "Too many parcels today, try again after 3 p.m." means send it again at 3 p.m. "Depot full" means wait a little, or hand it to a second courier you have already checked. "No such address" means a second try fails the same way, and so does a second courier: fix the address. "Your account's monthly limit is used up" means no courier will take it until the month ends or someone raises the limit. In this section, the note is the error's class, and the second courier is another model.

**What you will learn.** You practice this in Lab 30, Task 3.

- What has the SDK already done when an error reaches your code?
- Which class is the error, and what is the move for each?
- Which faults does a fallback suit?
- Which models may each environment end on?
- How do you know a stream ended right?

**Why it matters.** A retry that should have been a fix spends money and fails again. A fallback that should have been a wait hands Ana an answer from a model nobody tested. Both look like resilience in the code. Only the error's class says which one it is.

**At work.** On Tuesday, May 18, 2027, at 10:40 a.m., the check asks for row 4. Row 4 says which models each environment may end on.<!-- EDITOR: proposed in the spec, not yet in specs/labs/part-2-facts.md (staging's fallback list names a model copied from an example, which the suite never ran) --> <!-- OPEN: the fallback model in the run (spec, "What the drafter leaves OPEN") -->

### What has the SDK already done when an error reaches your code?

**It has retried the request twice, if the error was one it retries.** [21.9](../agent-loop-by-hand/when-the-loop-goes-wrong.md) said so: "Both SDKs do this for you, twice by default, for connection errors and for status codes 408, 409, 429 and 500 and above. So the loop itself does not retry."

Three details decide whether and how it waits. If the response has a `retry-after` header, the SDK waits that many seconds. If not, it backs off, from 0.5 to 8 seconds. And if the response has an `x-should-retry` header, the SDK follows it instead of the status.[^anthropic-errors][^anthropic-python-sdk] So when an error reaches your code, the fast retries are already spent. Your code's job is the next move, and that move depends on the class.

### Which class is the error, and what is the move for each?

**Read the status, the error type and, inside the type, its code. Then make one of five moves.** Each SDK raises a class of its own for each kind of error, so your code catches the class, not the number.[^anthropic-errors] The table's statuses, codes and moves come from Anthropic's errors and rate limits pages.[^anthropic-errors][^anthropic-rate-limits] The names below are the Python SDK's. TypeScript uses the same names, except for the client timeout.[^anthropic-errors][^anthropic-typescript-sdk]

Every error comes back with the same shape of body. This is Anthropic's own example, sent with status 429:[^anthropic-errors]

```json
{
  "type": "error",
  "error": {
    "type": "rate_limit_error",
    "message": "You have reached your API usage limits: ...",
    "details": { "error_code": "enforced_spend_limit_reached" }
  },
  "request_id": "req_018EeWyXxfu5pfWkrYcMdjWG"
}
```

The status is 429 and the type is `rate_limit_error`, as for any rate limit. Only the code inside, `error.details.error_code`, says this is the spend cap.

| Class | Status and type | After the SDK's retries |
| --- | --- | --- |
| Rate limit | 429 `rate_limit_error`, with `retry-after` | Wait as `retry-after` says, then try again |
| Ramp limit | 429, code `ramp_limit_exceeded`, under your rate limit, after a sharp rise in load | Wait as `retry-after` says, then grow the load by at most one step a minute |
| The tier's spend cap | 429, code `enforced_spend_limit_reached`, no `retry-after` | Never retry. Request a higher tier, or wait for the month |
| A spend limit you set | 400 `invalid_request_error` | Never retry. Raise or remove the limit, or wait until the time its message names |
| Overloaded | 529 `overloaded_error` | Back off, then try again, or fall back to a model the suite ran |
| Server error or timeout | 500 `api_error`, 504 `timeout_error`, or no answer in time | Back off, then try again, or fall back to a model the suite ran |
| Invalid request, not found or too large | 400 `invalid_request_error`, 404 `not_found_error`, 413 `request_too_large` | Never retry. Fix the request: for a 404 on a file id, upload the file in this workspace ([30.3](#303-images-documents-and-the-files-api)) |

Class names, for your `except` lines:

| Class | The SDK raises |
| --- | --- |
| Rate limit, ramp limit | `RateLimitError` |
| The tier's spend cap | `EnforcedSpendLimitReachedError`, a kind of `RateLimitError` |
| A spend limit you set, invalid request | `BadRequestError` |
| Overloaded | `OverloadedError` |
| Server error or timeout | `InternalServerError`, `GatewayTimeoutError`, or the client timeout |
| Not found, too large | `NotFoundError`, `ContentTooLargeError` |

A class also catches the classes inside it, so catch the narrower class first.[^anthropic-errors] Catch `OverloadedError` and `GatewayTimeoutError` before `InternalServerError`, which catches every server error. This handler gets the order wrong:

```python
# Wrong: the spend cap is a kind of RateLimitError, so it lands here
try:
    client.messages.create(...)
except anthropic.RateLimitError:
    time.sleep(5)
    retry()  # on the spend cap, this fails until access resumes
```

The fix is Anthropic's own order, the narrower class first:[^anthropic-errors]

```python
try:
    client.messages.create(...)
except anthropic.EnforcedSpendLimitReachedError:
    ...  # spend cap: retrying won't help until access resumes
except anthropic.RateLimitError:
    ...  # other 429s: back off and retry
```

- *Two 429s ask for opposite moves.* A rate limit clears in seconds, and `retry-after` says how many. The tier's spend cap pauses use until midnight UTC on the first day of the next month. "Retrying, including the SDK's automatic retries, fails until access resumes."[^anthropic-rate-limits] It carries no `retry-after`. So a loop that waits and retries on every 429 waits forever on the spend cap.
- *Tell them apart by the code.* On the Messages API, the code names the cause. Or catch `EnforcedSpendLimitReachedError` first.[^anthropic-errors] Other APIs, such as Claude Managed Agents, which runs the hosted worker, add no code to this 429.[^anthropic-errors] There, only the message tells the two causes apart, and Anthropic says not to match it in code. A spend-cap 429 keeps failing, so "limit your retries after a 429".[^anthropic-errors] The hosted worker's code does that after any 429.
- *Your own spend limit is a 400, not a 429.* A limit the organization or a workspace set below the tier's cap answers 400 `invalid_request_error`. Only its message tells it from a bad request. The message starts "You have reached your specified API usage limits", or, for a workspace's limit, "You have reached your specified workspace API usage limits", and it says when access resumes.[^anthropic-rate-limits] Brightline's limits are workspace limits ([Lab 23](../hosted-agents/lab.md), Task 0). You fix it in the Claude Console, where the organization's limits are set, not in the code. Brightline's budgets of $0.50 a question and $1.00 a review are different again. They are caps on one run ([23.5](../hosted-agents/a-budget-on-every-run.md), [Lab 23](../hosted-agents/lab.md)).
- *A server error is not always retried.* For a 500, retry only if the response's `x-should-retry` header is not `false`.[^anthropic-errors] A 503 that says `overloaded_error` counts as a server error, not as a 529.[^anthropic-errors]
- *A client timeout is the SDK giving up, not the API.* Python raises `APITimeoutError`, and TypeScript raises `APIConnectionTimeoutError`.[^anthropic-errors] Both SDKs wait 10 minutes by default. TypeScript can wait up to 60 minutes for a large request that does not stream.[^anthropic-python-sdk][^anthropic-typescript-sdk] Set your own deadline for a job that must finish before 7:10.

<!-- OPEN: whether a 529 counts against your rate limits. Neither the errors page nor the rate limits page says (facts 3.20). -->

<!-- FIGURE 30.4: A tree read top to bottom. Top box: "An error reaches your code, after the SDK's retries". Below it, one box: "Which class?". From it, five arrows pointing down, each labeled with its classes, to five move boxes in a row, numbered 1 to 5. Arrow "rate limit (429, retry-after)" to box 1 "Wait as retry-after says". Arrow "ramp limit (429, ramp_limit_exceeded)" to box 2 "Wait, then grow slowly". Arrow "overloaded (529), server error (500, 504), timeout" to box 3 "Back off and try again, or fall back to a model the suite ran". Arrow "invalid request (400), not found (404), too large (413)" to box 4 "Fix the request. Never retry. Never another model". Arrow "spend limit (429 enforced_spend_limit_reached, or a 400 whose message says you have reached your specified usage limits)" to box 5 "Raise the limit, or wait until access resumes". Under box 3 only, a small box "another model", with an arrow into it from box 3 labeled "only if the suite's report names it". No arrow runs from box 4, or from the invalid request arrow, to "another model". Alt text must say: the error has already been retried by the SDK, the five classes and their five moves as listed, that a 400 goes to box 5 only when its message starts "You have reached your specified API usage limits" or "You have reached your specified workspace API usage limits", and to box 4 otherwise, that a 404 not found goes to box 4, that only box 3 may go to another model and only to one the suite ran, and that an invalid request never goes to another model. -->

*Figure 30.4. After the SDK's retries, each class has one move. Only overload, server errors and timeouts may go to another model, and only to one the suite ran.*

### Which faults does a fallback suit?

**Only the ones where the same request could succeed somewhere else: overload, a server error and a timeout.** Here, a **fallback** means sending the same request to another model when the first one cannot answer. It suits a fault in the service, not a fault in the request.

- An invalid request goes to the next model just as invalid.
- A spend cap or a spend limit belongs to the organization, so every model is behind it.
- A rate limit or a ramp limit clears if you wait, and waiting keeps the answer on the model you tested.

The API has a setting called `fallbacks`, and it does not do this job. It is in beta, and "only a safety classifier decline triggers the fallback. A rate limit, overload, or server error on the requested model is returned to you as-is."[^anthropic-refusals-and-fallback] It is also missing on Amazon Bedrock, Claude Models on Google Cloud (Google managed), Microsoft Foundry, Claude Haiku 5.5 and the Message Batches API.[^anthropic-refusals-and-fallback] So a fallback on overload is your code's own list.

Which models go on that list is decided by one line from [25.10](../prompts-and-structured-output/defensive-parsing.md): "An answer from a model the suite never ran has passed no test." A fallback model must have passed the same suite as the pinned one. Otherwise the fallback trades a late answer for an untested one.

### Which models may each environment end on?

**The pin everywhere, and a fallback list only where the suite has run every model on it.** This is the fourth row of `docs/environments.md`:

| Row | Development: the laptop | Staging: CI and the staging workspace | Production: the portal |
| --- | --- | --- | --- |
| 4 Which models may answer | The pin, no fallback. Proof: the pin in `src/loop/config.json` (21.13) | The pin, and a fallback list used only after the SDK's retries, on overload, a server error or a timeout. Proof: each model in `config/prompts.yaml#staging.fallbacks` is named in the suite's report | Same |

<!-- EDITOR: the `model` and `fallbacks` keys in `config/prompts.yaml` are the spec's proposal (point 23), as round 2 changed it: the kit starts with the plan's file, and Tuesday's change adds them. Development's pin stays in Lab 21's `src/loop/config.json`. OPEN: the key path inside its `models` block is the kit's to name. -->

The laptop has no fallback, so an overload there shows up as an error you can see, and is not hidden behind another model's answer. Staging and production share one rule and one proof, so the check reads the suite's report and the fallback list side by side.

Tuesday's second failure was this cell, a fallback the suite never ran ([the point](#the-point)). The list stays empty until the suite has run that model, and an overload in staging backs off instead.

A pin must be an exact id. Before the 4.6 generation, a model id carries a date, such as `claude-haiku-4-5-20251001`, and an alias, such as `claude-haiku-4-5`. "Each alias points to the most recent dated snapshot for its minor version."[^anthropic-model-ids] So an alias in a config file is not a pin. The model behind it can change while no file of yours changes, and no check sees it. From the 4.6 generation on, the dateless id is itself the snapshot ([30.8](#308-how-todays-tools-realize-it)).

### How do you know a stream ended right?

**By the `message_stop` event, with the stop reason read from the `message_delta` before it.** This question fits no row of the table, because it is the same in every environment. [21.11](../agent-loop-by-hand/streaming.md) gave the rule "Expect an error in the middle", because "a stream can start with success and later send an error event." Three more facts finish it.

- *The message ends at `message_stop`, not at a block's stop.* A block's stop ends that block only, and a response can have several blocks.[^anthropic-streaming]
- *The stop reason comes last.* It is empty in `message_start` and arrives in a `message_delta` just before the end.[^anthropic-streaming] Read it every time. If it says `max_tokens`, the answer was cut short ([21.3](../agent-loop-by-hand/one-turn-request-response-and-stop-reason.md)). If it says `refusal`, the model declined, which is not an error, and [25.10](../prompts-and-structured-output/defensive-parsing.md) says what to discard.
- *An error after a 200 is not retried.* The request succeeded, the stream began, and then an error event arrived, such as `overloaded_error`.[^anthropic-streaming] The SDK raises it as an exception, and "the SDK doesn't retry an error in a stream."[^anthropic-errors]

So a stream that broke is handled twice. First, the half-finished output is incomplete: never show it as finished, and never add its half block to the conversation. Second, the error's class still decides the move. An overload mid-stream is an overload, with the same backoff and the same fallback rule as in the table. But now your code makes the first retry, because the SDK made none.

**The operating rule:** let the SDK make its retries, then move by the error's class. Wait on a rate limit, and never retry a spend cap or a bad request. Fall back only on overload, a server error or a timeout, and only to a model the suite ran.

**Do this now.** Ask your coding agent to show how this project handles errors. Copy this line:

> Find where this project catches errors from Claude's API. For each error class the SDK can raise, say what the code does after the SDK's own retries: wait, back off, fall back to another model, or fail. Name any place where a 400 is retried or sent to another model, any place where every 429 is treated the same, and any fallback model that the suite's report does not name. Say how the code handles an error in the middle of a stream. Change no file.

**Read next.** [30.5](#305-configuration-that-travels) asks which configuration each run reads, and what a default loads when nobody says.

[^anthropic-errors]: Errors, Claude API docs, Anthropic.
[^anthropic-python-sdk]: Python SDK, Claude API docs, Anthropic.
[^anthropic-rate-limits]: Rate limits, Claude API docs, Anthropic.
[^anthropic-typescript-sdk]: TypeScript SDK, Claude API docs, Anthropic.
[^anthropic-refusals-and-fallback]: Refusals and fallback, Claude API docs, Anthropic.
[^anthropic-model-ids]: Model IDs and versions, Claude API docs, Anthropic.
[^anthropic-streaming]: Streaming messages, Claude API docs, Anthropic.
