D2 · Tool Design & MCP › Cluster 3 · Tool Results & Error Handling

3.2 · Error Handling Patterns

Return errors, don't throw

CONCEPT Hand the failure back to Claude, don't crash the loop

When your tool fails — a 500 from an upstream API, a missing file, a bad argument — the wrong move is to let the exception bubble up and kill the request. The right move is to return the error to Claude as an ordinary tool_result with is_error: true. Claude reads that just like any other result and can recover: apologize, retry with corrected input, try a different tool, or ask the user for what's missing. Throwing keeps the failure inside your process; returning it puts the failure where the model can act on it.

Anti-pattern: raise/throw out of the tool handler. The agent loop dies, Claude never sees the error, and the user gets a stack trace instead of a graceful recovery.
Pattern: catch the exception, put its message in content, set is_error: true, and continue the conversation. The loop survives.

CONCEPT Recoverable vs. fatal

Not every error is equal. Sort them by whether Claude can fix it by trying again:

ClassExampleReturn to Claude?What Claude does
Recoverable — bad argsMissing required location; malformed date✅ is_error: true naming the problemRetries the tool with the fix (typically 2–3 attempts) before apologizing
Recoverable — transientRate limit; upstream 500; timeout✅ is_error: true with retry hintWaits/retries or explains to the user and offers to try later
Fatal for this toolAuth revoked; resource permanently gone✅ is_error: true, clear "cannot proceed" messageStops calling it; tells the user or switches approach
Harness-levelIrreversible action denied by your gate✅ Return a "DENIED / not executed" resultAdapts — doesn't keep hammering the blocked action
🔑 In every row you still return a tool_result. "Fatal" means Claude should stop retrying that tool — not that your code should throw. The error message is what tells it which.

CONCEPT Write the error for the model

Claude only knows what your content string says. A generic "failed" gives it nothing to reason with. An instructive message — what went wrong and what to try next — lets it recover without guessing.

✅ "Rate limit exceeded. Retry after 60 seconds." · ✅ "Error: missing required 'location' parameter."
⚠️ "failed" · ⚠️ "Error 500" — Claude can't tell if it should retry, fix an argument, or give up.

DIAGRAM Throw vs. return-as-result

flowchart TD T["Tool call fails"] --> Q{"How do you surface it?"} Q -->|"throw / raise"| CRASH["🔴 Exception escapes
loop dies, Claude blind"] Q -->|"tool_result + is_error:true"| BACK["Claude reads the error"] BACK --> R{"Recoverable?"} R -->|"bad args / transient"| RETRY["🟢 Retry with fix
(2–3 attempts)"] R -->|"fatal"| STOP["🟠 Stop this tool,
explain to user"] classDef ok fill:#d4edda,stroke:#28a745,color:#155724; classDef gate fill:#ffe8cc,stroke:#ff9f40,color:#9a4a0a; classDef bad fill:#f8d7da,stroke:#dc3545,color:#721c24; class RETRY ok; class STOP gate; class CRASH bad;

CODE Catch, then return is_error (don't re-raise)

def handle(block):
    try:
        result = run_tool(block.name, block.input)
        return { "type": "tool_result",
                 "tool_use_id": block.id,
                 "content": result }
    except ToolError as e:
        # Hand the failure to Claude — instructive text, not "failed".
        return { "type": "tool_result",
                 "tool_use_id": block.id,
                 "content": str(e),      # e.g. "Rate limit exceeded. Retry after 60s."
                 "is_error": True }        # Claude reads this and can recover

The resulting JSON block Claude receives:

{ "type": "tool_result",
  "tool_use_id": "toolu_01A09q90qw90lq917835lq9",
  "content": "ConnectionError: the weather service API is not available (HTTP 500)",
  "is_error": true }

TRADE-OFFS is_error return vs. throwing

✅ Return is_error: true

  • Loop survives; Claude can retry or adapt
  • Model-readable recovery path
  • One consistent shape for success and failure

⚠️ Throw the exception

  • Simple in trivial scripts
  • But: request dies, Claude never sees it
  • No recovery, no retry, opaque to the user
Note: this is for client tools. For server tools (web search, code execution), Anthropic handles errors internally — you don't send is_error results for those.

EXAM TRAPS

Trap: Letting the tool exception propagate. → That kills the agent loop and blinds Claude. Catch it and return is_error: true so the model can recover.
Trap: Treating a bad-argument error as fatal. → Missing/invalid parameters are recoverable — return the error naming the missing field and Claude retries (2–3 times) with it filled in.
Trap: Returning "failed". → Write instructive errors — what went wrong and what to try next — because the message is all Claude has to reason with.
Trap: Sending is_error results for server tools. → Server tools (web search, code execution) handle their own errors on Anthropic's side; you only return is_error for client tools you execute.

PRACTICE

Q1 · Your weather API returns HTTP 500. Throw, or return something — and what exactly?

Return a tool_result with is_error: true and an instructive content like "weather service unavailable (HTTP 500). Retry later." Throwing would kill the loop and hide the failure from Claude.

Q2 · Claude calls get_weather with no location. Is that recoverable, and how do you respond?

Recoverable. Return is_error: true with "Error: Missing required 'location' parameter." Claude will re-call the tool with the location filled in (retrying a couple of times before giving up). strict: true on the tool schema prevents this class entirely.

Q3 · Why is a vague "error" string worse than a specific one, given Claude can't see your logs?

The content string is the model's only view of the failure. A specific message ("retry after 60s", "auth expired, re-authorize") tells it whether to retry, fix an argument, or stop — a bare "error" leaves it guessing.