30.4 Errors by class: retry, fall back or fix
- Approved by
- Panaversity ·
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.
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 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.12 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.1 The table's statuses, codes and moves come from Anthropic's errors and rate limits pages.13 The names below are the Python SDK's. TypeScript uses the same names, except for the client timeout.14
Every error comes back with the same shape of body. This is Anthropic's own example, sent with status 429:1
{
"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) |
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.1 Catch OverloadedError and GatewayTimeoutError before InternalServerError, which catches every server error. This handler gets the order wrong:
# 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 resumesThe fix is Anthropic's own order, the narrower class first:1
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-aftersays 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."3 It carries noretry-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
EnforcedSpendLimitReachedErrorfirst.1 Other APIs, such as Claude Managed Agents, which runs the hosted worker, add no code to this 429.1 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".1 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.3 Brightline's limits are workspace limits (Lab 23, 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, Lab 23). - A server error is not always retried. For a 500, retry only if the response's
x-should-retryheader is notfalse.1 A 503 that saysoverloaded_errorcounts as a server error, not as a 529.1 - A client timeout is the SDK giving up, not the API. Python raises
APITimeoutError, and TypeScript raisesAPIConnectionTimeoutError.1 Both SDKs wait 10 minutes by default. TypeScript can wait up to 60 minutes for a large request that does not stream.24 Set your own deadline for a job that must finish before 7:10.
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."5 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.5 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: "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 |
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 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."6 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).
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 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.7 - The stop reason comes last. It is empty in
message_startand arrives in amessage_deltajust before the end.7 Read it every time. If it saysmax_tokens, the answer was cut short (21.3). If it saysrefusal, the model declined, which is not an error, and 25.10 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.7 The SDK raises it as an exception, and "the SDK doesn't retry an error in a stream."1
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 asks which configuration each run reads, and what a default loads when nobody says.
Check yourself
Question 1 / 6
0 answered
An error reaches the worker's code after the SDK's retries. For which one may the code send the request to a fallback model?
Sources
- Owner
- Panaversity