Debugging a Claude App: Three Error Types, the Recovery Each One Earns, and the First Failing Row
One retry loop for every failure spends 15 calls on five tickets and logs one word: failed. Classify each error as transient, request or output, give each its own recovery, and write a trace row per step: the same five tickets take 9 calls, and the first failing row shows where each one broke.
What you will learn
- Sort a failed call into transient, request or output from its status code and error type
- Match the recovery to the type: capped retry, no retry, or one re-ask
- Write a trace with one row per step and the request id of every call
- Find where a ticket broke by reading the first failing row
Before you start
- The Claude Messages API: your first call
- Python try/except
A support agent's tickets keep failing. One error says overloaded. Another says invalid request. And some tickets come back fine, with an answer nobody can use.
Most apps push all of these through one retry loop and log one word: failed. Nobody can tell what broke. In this article we sort failures into three types, give each type the recovery it deserves, and write a trace you can actually read. The question we answer is: why did that ticket fail?
One retry loop hides three failures
Here is the version we are replacing, naive_flow.py:
def handle(ticket, client, sleep=None):
req = build_request(ticket)
for attempt in range(4):
try:
r = client.messages.create(**req)
json.loads(r.content[0].text)
return OK
except Exception:
pass
return FAILED
Three problems hide in eight lines:
- Four tries, whatever went wrong. It never asks why.
- The JSON parse sits in the same
try. A bad answer and a failed call look the same. except Exceptioncatches everything. A busy API and a broken request take the same path.
Take one ticket with a deep question and extended thinking turned on. The request uses a thinking setting this model doesn't accept, so the API answers 400. The loop sends the same request again, gets the same 400, three more times, and logs failed. Four calls on a request that can never work.
A parcel that comes back
Think of a parcel that comes back to the depot with a note.
- "Depot jammed, come back later." You wait and resend. That is a transient error.
- "The address is wrong." Resending changes nothing. You fix the label. That is a request error.
- "The wrong item is inside." The parcel did arrive. You send it back once, with a note. That is an output problem.
Three notes, three different next moves. You would not resend a parcel with the wrong address.
Three kinds of failure
triage.py: read the error, pick the class
"""Error types and the recovery each one earns."""
import anthropic
RECOVERY = {
"ok": "deliver the reply",
"transient": "wait, then retry (capped)",
"request": "no retry: fix the request",
"output": "re-ask once, name the problem",
}
def classify(err):
"""Read the error type, then pick the recovery class."""
if isinstance(err, anthropic.APIStatusError):
if err.status_code in (429, 500, 504, 529):
return "transient"
return "request"
# a dropped connection or a timeout is transient too
return "transient"
def describe(err):
"""The status and the error type from the body."""
etype = err.body["error"]["type"]
return f"{err.status_code} {etype}"
The status decides the class. Any other 4xx means the request itself is wrong. describe pulls the error type out of the body, such as invalid_request_error or overloaded_error.
desk_flow.py: one recovery per type, one row per step
MAX_ATTEMPTS = 3
REASK = "That was not valid JSON. Reply with JSON only."
def handle(ticket, client, sleep=time.sleep):
log = Trace(ticket["id"])
req = build_request(ticket)
log.ok("build_request", f"model {req['model']}")
for attempt in range(1, MAX_ATTEMPTS + 1):
try:
r = client.messages.create(**req)
break
except anthropic.APIError as err:
kind, why = classify(err), describe(err)
log.fail("call_claude", why, err.request_id)
if kind == "request":
return done(kind, why, log)
sleep(2 ** attempt)
else:
return done("transient", "gave up, queue it", log)
log.reply(r)
if not valid(r):
log.fail("parse_reply", "not valid JSON")
reask(req, client, log, r)
return done("output", "delivered", log)
log.ok("parse_reply", "valid JSON")
if attempt > 1:
return done("transient", "retried, delivered", log)
return done("ok", "", log)
- A request error stops right there. No retry.
- A transient error waits a little longer each time, up to three tries, then the ticket is queued.
- If the call worked but the text isn't JSON, the flow re-asks once and says what was wrong.
- Every step writes a row, and every failed call keeps its
request_id.
The Trace class is tiny: a list of rows with step, status, detail and request id, plus a method that returns the first row whose status is fail.
Same five tickets, both flows
The lecture runs both flows against a stand-in for Claude: the real Anthropic SDK talking to a mock transport with scripted replies and made-up request ids, so no API key is needed. The output below is from that stand-in, not from a live model.
naive flow
T-201 ok -> deliver the reply | calls 1
T-202 ok -> deliver the reply | calls 2
T-203 failed -> log: failed | calls 4
T-204 failed -> log: failed | calls 4
T-205 failed -> log: failed | calls 4
triaged flow
T-201 ok -> deliver the reply | calls 1
T-202 transient -> wait, then retry (capped), retried, delivered | calls 2
T-203 request -> no retry: fix the request, 400 invalid_request_error | calls 1
T-204 output -> re-ask once, name the problem, delivered | calls 2
T-205 transient -> wait, then retry (capped), gave up, queue it | calls 3
calls: naive 15 | triaged 9
Nine calls against fifteen. More useful still: the naive flow lost T-204, a ticket a single re-ask could save, and it can't tell you anything about the other two.
Read the first failing row
trace T-202
1 build_request ok model claude-sonnet-5-5 -
2 call_claude fail 529 overloaded_error req_0002
3 call_claude ok 200 end_turn req_0003
4 parse_reply ok valid JSON -
first failure: call_claude, 529 overloaded_error, req_0002
trace T-203
1 build_request ok model claude-sonnet-5-5 -
2 call_claude fail 400 invalid_request_error req_0004
first failure: call_claude, 400 invalid_request_error, req_0004
trace T-204
1 build_request ok model claude-sonnet-5-5 -
2 call_claude ok 200 end_turn req_0005
3 parse_reply fail not valid JSON -
4 call_claude ok 200 end_turn req_0006
5 parse_reply ok valid JSON -
first failure: parse_reply, not valid JSON, -
- T-202: the call failed with a 529, then passed. A busy service, healed by waiting.
- T-203: one failing call, a 400, with its request id. Go fix the request (here, the thinking setting).
- T-204: the call row is fine; the parse row failed. The trouble is in the output, not the transport.
Find the first failing row and you know where to look. For a bigger version of this idea, with a span per stage, see observability and tracing for LLM apps.
Common mistakes
- Raising the SDK's max retries. A 400 fails the same way every time. More retries just cost more.
- Logging only the final exception message. Then there's no step and no request id to follow.
- Re-asking the model after any failure. An overloaded API needs time, not a new prompt.
- Parsing inside the call's try block. A bad answer then looks like a network error.
- Retrying forever. Cap the tries, then queue the ticket.
Quick recap
| Type | Signal | Recovery |
|---|---|---|
| Transient | 429, 500, 504, 529, timeout | Wait, retry with a cap, then queue |
| Request | 400, 401, 403, 404, 413 | Fix the request, no retry |
| Output | 200, but not the shape you asked for | Re-ask once, naming the problem |
| Trace | One row per step, with request ids | Read the first failing row |
For the retry policy in depth (what the SDK already retries, retry-after, timeouts and fallbacks), see Anthropic SDK timeouts, retries and error classes. This article adds the output type and the trace on top.
Try it yourself
Open the error handling in one of your own Claude calls. Does a 400 get retried? Does a reply that isn't JSON look the same as a timeout in your logs? Add a classify function and one trace row per step, then break the request on purpose and read the first failing row.
Related course on Udemy
Claude Certified Developer - Foundations (CCDV-F) Exam Prep
Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)Related posts
The Claude Messages API: Your First Call, Field by Field
One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.
Claude Tool Use: How tool_use and tool_result Work in the Messages API
Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.
Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.
Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.