Skip to main content
Module 4: Mastery 2 / 6
Advanced S20 Error Handling Recovery

Error Recovery

Build retry logic, error classification, and fallback strategies.

March 20, 2026 18 min read
Verified Curriculum reviewed: Oct 21, 2026

What You’ll Learn

Errors are inevitable in agent workflows. APIs return 429s. Builds fail. Tests break. Files are missing. What separates a fragile script from a resilient agent is how it responds to failure --- not whether it encounters it.

By the end, you’ll understand:

  • How to classify errors into actionable categories
  • The retry pattern with exponential backoff
  • Fallback strategies when the primary approach fails
  • How Claude Code turns errors into information
  • Which failures Claude Code already recovers from on its own
  • Common failure modes and their recovery patterns

The Problem

A naive agent treats every error the same way: it stops. But not all errors are equal.

Error: ENOENT: no such file or directory     ← Wrong path, fixable
Error: 429 Too Many Requests                 ← Temporary, just wait
Error: Cannot find module 'express'          ← Missing dependency, install it
Error: SyntaxError: Unexpected token         ← Code bug, must fix
Error: EPERM: operation not permitted         ← Needs user action

Each requires a completely different response. Stopping on every error wastes time; retrying every error wastes even more. The key is classification: understanding what kind of error you are dealing with before deciding what to do.

How It Works

Error Classification

Every error falls into one of three categories:

┌──────────────────────────────────────────────────┐
│            Error Classification                   │
│                                                   │
│  TRANSIENT → Retry with backoff                   │
│  │  Rate limits, network errors, timeouts,        │
│  │  server 5xx. Will succeed if you wait.         │
│  │                                                │
│  PERMANENT → Change approach                      │
│  │  File not found, syntax error, type mismatch,  │
│  │  missing module. Retrying won't help.          │
│  │                                                │
│  USER-ACTIONABLE → Ask the user                   │
│     Permission errors, auth required, config      │
│     missing, ambiguous requirements. The agent    │
│     cannot resolve these alone.                   │
│                                                   │
└──────────────────────────────────────────────────┘

The Retry Pattern

For transient errors, use exponential backoff:

Attempt 1: Try → Fails (429) → Wait 1s
Attempt 2: Try → Fails (429) → Wait 2s
Attempt 3: Try → Fails (429) → Wait 4s
Attempt 4: Try → Succeeds!

  Max retries: 3-5 for most operations
  Max wait: cap at 30-60 seconds
  Doubling wait prevents hammering rate-limited APIs

The wait doubles with each attempt, which gives the other system time to recover:

┌────────────────────────────────────────────┐
│         Exponential Backoff                 │
│                                             │
│  Attempt   Wait    Total elapsed            │
│  ───────   ────    ─────────────            │
│     1       0s          0s                  │
│     2       1s          1s                  │
│     3       2s          3s                  │
│     4       4s          7s                  │
│     5       8s         15s                  │
│     6      16s         31s  ← usually stop  │
│                                             │
│  Max retries: 3-5 for most operations       │
│  Max wait: cap at 30-60 seconds             │
│                                             │
└────────────────────────────────────────────┘

Retry only operations that are safe to repeat. Re-sending a read is harmless; re-running a step that already changed something, such as a deploy or a database write, can do the work twice.

Fallback Strategies

When the primary approach fails permanently, try alternatives:

┌──────────────────────────────────────────────────┐
│           Fallback Chain                          │
│                                                   │
│  Primary: npm install express                     │
│     │  FAILS (npm not found)                      │
│     ▼                                             │
│  Fallback 1: yarn add express                     │
│     │  FAILS (yarn not found)                     │
│     ▼                                             │
│  Fallback 2: pnpm add express                     │
│     │  SUCCEEDS → Continue with pnpm              │
│     ▼                                             │
│  All failed → Report what was tried               │
│                                                   │
└──────────────────────────────────────────────────┘

Better still, gather evidence before guessing: a pnpm-lock.yaml, yarn.lock, or package-lock.json already tells you which package manager the project uses.

Fallbacks work at every level:

File Reading:     Try config.ts → config.js → config.json → search
Build Commands:   Try pnpm build → npm run build → yarn build → read package.json
Test Runners:     Try pnpm test → npx jest → npx vitest → find config

How Claude Code Handles Tool Errors

When a tool call fails, the error is returned as a tool_result, just like a successful result. The AI reads it and adapts:

┌──────────────────────────────────────────────────┐
│        Error as Tool Result                       │
│                                                   │
│  AI calls: Bash("cat src/auth.ts")                │
│                                                   │
│  Tool returns:                                    │
│    "cat: src/auth.ts: No such file or directory"  │
│    is_error: true                                 │
│                                                   │
│  AI reasons: "Wrong path. Let me search."         │
│                                                   │
│  AI calls: Bash("grep -rl auth src                │
│                  --include='*.ts'")               │
│                                                   │
│  Tool returns:                                    │
│    "src/middleware/authenticate.ts"               │
│    "src/lib/auth-utils.ts"                        │
│                                                   │
│  AI adapts: reads the correct file                │
│                                                   │
└──────────────────────────────────────────────────┘

The search runs through Bash because, on macOS, Linux, and WSL, Claude Code leaves the dedicated Grep and Glob tools out of the default tool set and searches with grep and find in its shell instead. On Windows, or when a subagent’s tools list names them, Claude uses the Grep and Glob tools.

This is the “error as information” principle. The error is not a stop signal --- it is data that helps the AI make a better next decision.

What Claude Code Already Recovers From

Some recovery happens before an error ever reaches you. Design your own rules around it rather than duplicating it:

  • Automatic API retries. Claude Code retries transient failures --- server errors, 529 overloaded responses, timeouts, dropped connections, and temporary 429 throttles --- up to 10 times with exponential backoff before showing an error. The spinner shows Retrying in Ns · attempt x/y while it waits. CLAUDE_CODE_MAX_RETRIES changes the count; lower it in scripts to surface failures faster.
  • No retry where repeating is unsafe. If a failure arrives after Claude has already completed a tool call in that response, Claude Code keeps what was completed and continues the turn instead of re-sending the request, because a re-send could run the same tool calls twice. A TLS certificate failure is reported on the first attempt, since only fixing the certificate setup helps.
  • Fallback models. claude --fallback-model sonnet,haiku (or the fallbackModel setting) switches to the next model in the chain when the primary model is overloaded or unavailable, for the current turn only. Authentication, billing, and rate-limit errors never trigger a switch.
  • Undo. Claude Code checkpoints file edits before each prompt you send. Run /rewind (or press Esc twice on an empty prompt) to restore code, the conversation, or both. Changes made through Bash commands aren’t tracked, so keep git as the recovery boundary for those.

Your own retry logic belongs to your tools and scripts. Wrapping Claude Code’s API calls in another retry loop only multiplies the waiting.

The Error Recovery Loop

┌──────────────────────────────────────────┐
│          Error Recovery Loop              │
│                                           │
│  1. Attempt the operation                 │
│          │                                │
│          ▼                                │
│  2. Succeed? YES → Continue               │
│              NO  → Classify               │
│          │                                │
│          ▼                                │
│  3. TRANSIENT → Retry (max 3-5x)          │
│     PERMANENT → Try fallback              │
│     USER-ACT  → Report and ask            │
│          │                                │
│          ▼                                │
│  4. Recovery worked? YES → Continue       │
│                      NO  → Escalate       │
│          │                                │
│          ▼                                │
│  5. Report what was tried and what failed │
│                                           │
└──────────────────────────────────────────┘

Key Insight

Good error recovery is what separates a fragile script from a resilient agent. The AI should treat errors as learning opportunities, not stop conditions.

When an error occurs, it contains information:

  • “File not found” tells you the path is wrong --- search for the right one
  • “Module not found” tells you a dependency is missing --- install it
  • “Type error” tells you the code has a bug --- read the types and fix it
  • “Permission denied” tells you the operation needs elevated access --- ask the user

Each error narrows the solution space. An agent that reads errors carefully and adapts can solve problems that a simple script never could.

The most common mistake in agent design is treating all errors as fatal. The second is retrying everything indiscriminately. Classification is the skill that makes recovery effective.

Hands-On Example

Building a Resilient Package Installation Flow

Here is how you might ask Claude Code to handle a real-world install with recovery built in:

Install the "sharp" image processing library in this project.
If it fails, diagnose the error and try alternative approaches.
Stop after three failed attempts and report what you tried.

The agent’s behavior with good error recovery:

Step 1: pnpm add sharp
  → Error: no prebuilt binary loaded; the source build failed
    (no libvips / compiler toolchain)
  → Classify: PERMANENT (environment problem; retrying won't help)

Step 2: Fallback → Restore the prebuilt-binary path
  → Read the error and sharp's install notes: is the package
    manager skipping optional dependencies, or is this
    platform unsupported?
  → Fix the configuration and reinstall once
  → Still fails

Step 3: Fallback → Try an alternative library
  → pnpm add jimp (pure JavaScript, no native deps)
  → Succeeds!

Step 4: Update code to use jimp instead of sharp
  → Adjust imports and API calls
  → Run tests to verify

Step 5: Report
  → What failed, what was tried, and the trade-off
    (no native dependency, but possibly slower)

Common Failure Modes and Recovery

FailureClassificationRecovery
ENOENT: file not foundPermanentSearch for file, check spelling
429 Too Many RequestsTransientExponential backoff, max 5 retries
EACCES: permission deniedUser-actionableReport, suggest chmod or sudo
Build failed: type errorPermanentRead error, fix the type mismatch
Test failed: assertionPermanentRead test, fix logic or update test
Connection timeoutTransientRetry with longer timeout
Module not foundPermanentInstall missing dependency
Out of memoryUser-actionableSuggest more memory or batch processing
Git conflictPermanentRead conflict markers, resolve
Lint errorPermanentRead the rule, fix the violation
API Error: Repeated 529 OverloadedTransient (Claude Code already retried)Wait, check status.claude.com, or switch models with /model

Error-Aware CLAUDE.md Instructions

Encode recovery strategies directly in your project instructions:

# Error Recovery Rules

When a build fails:
1. Read the FULL error output, not just the last line
2. If it's a type error, check the relevant type definitions
3. If it's a missing import, search for the correct path
4. If it's a dependency issue, run pnpm install first

When tests fail:
1. Run the failing test in isolation first
2. Read both the test and the implementation
3. Determine if the test or the code is wrong
4. Fix the root cause, not the symptom

Never retry more than 3 times for the same error.
If stuck after 3 attempts, report what you tried.

This gives Claude Code an explicit recovery playbook instead of relying on implicit reasoning.

What Changed

Without Error RecoveryWith Error Recovery
Agent stops at first errorAgent classifies and adapts
All errors treated the sameTransient, permanent, user-actionable
No retry logicExponential backoff for transient errors
No fallback optionsAlternative approaches tried
Errors are failuresErrors are information
User must intervene constantlyAgent self-heals when possible

Next Session

Session 21 covers Cost Optimization --- how to select the right model for each task, manage tokens efficiently, and design workflows that balance quality and cost.