Module 84: AI APIs

Lesson 5 of 5 · 15–25 minutes

Error handling

🏠The everyday picture

A delivery company plans for traffic jams, wrong addresses and closed shops. A good one retries sensibly, tells the customer what's happening, and doesn't send ten drivers to the same address.

📘What it really is

try {
  const response = await client.messages.create({ /* ... */ });
  if (response.stop_reason === "refusal") return politeRefusal();
  if (response.stop_reason === "max_tokens") log.warn("answer truncated");
  // use the answer
} catch (error) {
  if (error instanceof Anthropic.RateLimitError) {
    return busyMessage();            // already retried by the SDK; tell the user to try shortly
  } else if (error instanceof Anthropic.AuthenticationError) {
    log.error("AI key invalid");      // configuration problem: alert yourself
    return unavailableMessage();
  } else if (error instanceof Anthropic.APIError) {
    log.error({ status: error.status }, "AI API error");
    return unavailableMessage();
  }
  throw error;
}

🖱️Try it

Add typed error handling to your assistant route. Test it: use a wrong key (expect an authentication error and a friendly message), set max_tokens very low (detect truncation), and simulate an outage by pointing at a bad address or throwing in a test. Check the rest of the CRM keeps working in each case.

✅Quick check

Which errors should be retried, and which shouldn't?

Show the answer

Retry rate limits, overload, server errors and timeouts (with backoff and a limit); don't retry bad requests or authentication errors; fix them.

What should your app do if the AI provider is down?

Show the answer

Keep the rest of the app working and show a clear, helpful message (or use a fallback).

← PreviousCost and speed
ProLearners Assist