Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Claude
  • CLAUDE.md, settings.json and Plugins: Which Claude Code File Advises, Which Enforces, Which Packages
  • Authoring a Claude Skill: SKILL.md, Frontmatter, Progressive Disclosure and the Description That Triggers It
  • One Change, Four Environments: Where a Claude Config Edit Lands in Dev, Staging, Prod and CI
  • Claude in the SDLC: Prompts in Git, a Change Gate by Path, a Claude Review That Advises and a Person Who Merges
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Choosing a Claude Code Extension: Skill, Hook, Rules File, Subagent, Slash Command or Plugin
  • Rolling Out Claude Code to a Team: Settings Precedence, dontAsk in CI, a Hook for Every-Time Rules and a Plugin for Five Repos
  • A Claude Code Review Bot in CI: Headless -p, JSON Findings, Team Rules in Git and a Person on the Merge
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • The Claude Messages API: Your First Call, Field by Field
  • Claude Tool Use: How tool_use and tool_result Work in the Messages API
  • Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
  • Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
  • Claude Streaming Events: The Event Order, message_stop, Tool Arguments, Stop Reasons and a WebSocket Relay
  • Images, PDFs and Thinking Blocks in the Claude Messages API: Typed Blocks In, Typed Blocks Out
  • Getting Data Into Claude: PDF Documents, the Files API, Search Results and Citations
  • Opus, Sonnet or Haiku: Pick the Claude Model per Job, and Test the Request When a New Release Arrives
  • Adaptive Thinking and Effort in Claude: Two Dials, Set per Workload, and the Thinking Block You Must Pass Back
  • Claude Cost Tracking From usage: Count Before, Cap During, Read After, Then Find the Line That Drives the Bill
  • Claude Cache Breakpoints: Where to Put cache_control, How to Move It With the Chat, and Why the Reads Stay at Zero
  • Claude Message Batches or Real Time: Choose by Who Is Waiting, Match by custom_id, Resend Only the Failures
  • Calling Claude Through Amazon Bedrock, Google Cloud and Microsoft Foundry: Same Call, Different Door
  • The Life Cycle of a Claude App: Six Phases, a Model That Retires, and a Release Gate for Every Change
  • Pinning Claude Model IDs and Upgrading Safely: One Change at a Time, a Golden-Set Replay and a Staged Rollout
  • Content Boundaries and Schema Design for Claude: Fence the Input in a Tag, Let the Output Say I Don't Know
  • The Agentic Loop and stop_reason: Keep Turning on tool_use, Stop on end_turn, Cap the Turns
  • The Claude Agent SDK: query(), ClaudeAgentOptions and @tool, in Python and TypeScript
  • Fix the Agent: Four Broken Claude Agent SDK Configs, From the Symptom to the One Wrong Line
  • Claude Managed Agents: Cloud Sandbox, Self-Hosted Sandbox or Self-Hosted Service
  • Agent SDK Hooks for Deterministic Actions: PreToolUse, PostToolUse, and Four Hooks That Fail Silently
  • Memory and Context-Window Patterns for Claude Agents: Context Editing, Compaction and the Memory Tool
  • Reading an Agent Trace: Five Signatures, Five Missing Patterns, and How Long a Fact Must Live
  • Tool Descriptions for Claude: How Claude Picks a Tool, and How to Stop It Picking the Wrong One
  • Tool Input Schemas and Error Responses for Claude: Required Fields, Enums, is_error and a Retry Flag
  • Tool Response Shaping and a Lean Tool Set: Give Claude a Sticky Note, Not the Filing Cabinet
  • Fix the Tool Schema: Read the Trace, Fix the Card, Re-Run (Four Real Schema Bugs)
  • Client Tools, Server Tools and Approval Gates: Who Runs the Tool, and Who Says Yes First
  • Built-in Tool, Custom Tool, Skill or MCP Server? Pick the Lightest One That Fits
  • System Prompt or User Turn: Where Each Instruction Goes, and Output Limits Your Code Enforces
  • Refine the Prompt One Line at a Time, Then Clean and Fence the Customer's Text
  • Prompt Revision Driven by Evals: Name the Cause, Change One Thing, Rerun the Whole Suite
  • Long-Running Sessions: Compact, Prune, Isolate or Start Fresh, Decided by Naming the Failure
  • Context Isolation Through Subagents: Read the Logs Elsewhere, Keep One Line
  • Defensive Parsing of Claude Replies: Check the Stop Reason, Read the Block or the Text, Then Validate the Values
  • Full Context or Retrieval: Choose by Corpus Size, Cost and Freshness
  • Skepticism Toward Confident Output: Check the Quote, the Record and the Sum Before You Send
  • Debugging a Claude App: Three Error Types, the Recovery Each One Earns, and the First Failing Row
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Fix the Cause, Not the Symptom: Four Recovery Drills for an LLM App, Each Checked on a New Input
  • Integration Layer or Model Output? Three Taps and Three Questions to Find Where a Wrong Answer Lives
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Designing an Overnight Document Pipeline on Claude: Batch Lane, Live Lane, a Cached Prefix and a custom_id Reconcile
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • From Requirement to Design for a Claude App: Eight Requirements, Five Elements and a Trace With No Gaps
  • Build a Claude Refund App: the Messages API, Two Tools, an MCP Server and a Hook in One Loop
  • Ship a Claude App: an Eval Gate, Two Guardrail Layers, a Cost Check From usage and a Pinned Model
  • Lab: a 30-Case Golden Set, a Calibrated Judge and a Per-Slice CI Gate on a Claude Refund App
  • Lab: Cut a Claude App's Bill by 62 Percent With Usage Data, Layered Cache Breakpoints and a Batch Job
  • Lab: Three Planted Bugs in a Claude App, a Vague Prompt, a Mistyped Tool Schema and a Broken Stream Handler
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Lab: Harden a Claude App, an Uncalibrated Judge, a Retry Loop That Retries Everything and a Hook Matcher With a Gap
  • Lab: Turn a Claude App Into a Reusable Template, One Pinned Model Id, No Key in Code and Evals Built From Data
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  1. Blog
  2. /
  3. Claude
  4. /
  5. Building with the Claude API

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.

Chaand Sheikh

·27 November 2026Building with the Claude API

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 Exception catches 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

Error type picks the recovery Transient 429, 500, 504, 529 or a timeout The service is busy. It may heal. Wait, then retry (capped) Request 400, 401, 403, 404, 413 The request is wrong. Repeating can't help. Fix the request, no retry Output 200, end_turn but not the JSON asked for The call worked. The answer didn't. Re-ask once, name the problem
Read the type first. The type picks the recovery. Every API error body carries its type and a request id.

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

TypeSignalRecovery
Transient429, 500, 504, 529, timeoutWait, retry with a cap, then queue
Request400, 401, 403, 404, 413Fix the request, no retry
Output200, but not the shape you asked forRe-ask once, naming the problem
TraceOne row per step, with request idsRead 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Claude · 48 of 66

Previous
Skepticism Toward Confident Output: Check the Quote, the Record and the Sum Before You Send
Next post
Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency

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.

On this page

  • One retry loop hides three failures
  • A parcel that comes back
  • Three kinds of failure
  • triage.py: read the error, pick the class
  • desk_flow.py: one recovery per type, one row per step
  • Same five tickets, both flows
  • Read the first failing row
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.