Lesson

Error Recovery in Agent Loops

When building complex, long-running Agent loops, errors are inevitable. A 3rd-party API might timeout, Zod might reject a malformed JSON payload, or Claude might hallucinate a tool argument.

If your Node.js application crashes every time one of these minor hiccups occurs, your Agent is useless.

You must build Self-Healing Agent Loops.

The Basic try/catch is Not Enough

If you use a simple try/catch block, you prevent the server from crashing, but you usually just return an error to the user: "Sorry, the AI failed."

A self-healing loop catches the error, but instead of giving up, it feeds the error back to the AI and asks the AI to fix it.

Building a Self-Healing Loop

Let's look at a recursive function pattern that gives Claude 3 tries to get it right.

async function executeAgentTask(userPrompt, retryCount = 0) {
  const MAX_RETRIES = 3;

  try {
    // 1. Call the API
    const response = await anthropic.messages.create({ ... });
    
    // 2. Parse and Validate the output
    const data = JSON.parse(response.content[0].text);
    const validatedData = myZodSchema.parse(data);
    
    // If we reach here, it worked! Return the good data.
    return validatedData;

  } catch (error) {
    // 3. Catch the error
    if (retryCount >= MAX_RETRIES) {
      throw new Error("Agent failed completely after 3 retries.");
    }

    console.log(`Agent failed. Retrying... (${retryCount + 1}/${MAX_RETRIES})`);

    // 4. The Magic: Tell Claude what went wrong!
    const errorCorrectionPrompt = `
      Your previous attempt failed with this error: ${error.message}
      Please review the error and rewrite your output to fix the mistake.
    `;

    // Recursively call the function again, passing the error prompt
    return executeAgentTask(errorCorrectionPrompt, retryCount + 1);
  }
}

Why This Works

LLMs are excellent debuggers. If Claude accidentally outputs {"age": "forty"} instead of {"age": 40}, Zod will throw an error: "Expected number, received string".

When you feed that exact error string back into Claude in Step 4, Claude's reasoning engine kicks in. It looks at its previous output, reads the error, instantly understands the mistake, and outputs the corrected integer on the next loop.

By implementing this self-healing architecture, an Agent that would have failed 20% of the time in production will now succeed 99% of the time, seamlessly recovering from its own mistakes without the human user ever knowing.

Ready to test your understanding? Take the quiz to reinforce what you learned.

© 2026 Ant Skillsv.26.07.07-23:01
Ant Skills - Lesson