← Blog

Claude API Error Handling in TypeScript: Full Example

2026-11-21 · 5 min read · SubToAPI Team

If you're calling the Claude API from a TypeScript backend, you need a plan for what happens when a request fails. Rate limits, overloaded models, malformed requests, and network timeouts aren't edge cases — they happen in production every day. This article gives you a working TypeScript pattern for catching, classifying, and retrying Claude API errors correctly.

The short answer: wrap every call in a typed error handler that inspects the HTTP status code, distinguishes retryable from non-retryable failures, implements exponential backoff with jitter for 429s and 529s, and surfaces a clean error object to your application code instead of a raw fetch exception. Below is the full implementation.

Understanding Claude API error types

Claude's API returns structured errors with an HTTP status code and a JSON body describing the error type. The main ones you'll encounter:

The critical design decision is separating retryable errors (429, 500, 529, network timeouts) from permanent ones (400, 401, 403, 404, 413). Retrying a 400 request a hundred times will never succeed — it'll just burn time and quota.

A typed error class

Start by defining a custom error class that carries the status code and error type, so downstream code can branch on it without parsing strings:

export class ClaudeApiError extends Error {
  constructor(
    message: string,
    public readonly status: number,
    public readonly errorType: string,
    public readonly retryable: boolean
  ) {
    super(message);
    this.name = "ClaudeApiError";
  }
}

const RETRYABLE_STATUSES = new Set([429, 500, 529]);

function parseErrorType(status: number): string {
  const map: Record<number, string> = {
    400: "invalid_request_error",
    401: "authentication_error",
    403: "permission_error",
    404: "not_found_error",
    413: "request_too_large",
    429: "rate_limit_error",
    500: "api_error",
    529: "overloaded_error",
  };
  return map[status] ?? "unknown_error";
}

The request wrapper with retry and backoff

This function performs the fetch, classifies failures, and retries with exponential backoff plus jitter — a standard pattern for any rate-limited API, not just Claude:

interface RetryOptions {
  maxRetries?: number;
  baseDelayMs?: number;
}

async function callClaudeWithRetry(
  url: string,
  body: Record<string, unknown>,
  apiKey: string,
  opts: RetryOptions = {}
): Promise<any> {
  const maxRetries = opts.maxRetries ?? 4;
  const baseDelayMs = opts.baseDelayMs ?? 500;

  let attempt = 0;

  while (true) {
    try {
      const res = await fetch(url, {
        method: "POST",
        headers: {
          "content-type": "application/json",
          "x-api-key": apiKey,
          "anthropic-version": "2023-06-01",
        },
        body: JSON.stringify(body),
      });

      if (res.ok) {
        return res.json();
      }

      const payload = await res.json().catch(() => ({}));
      const errorType = payload?.error?.type ?? parseErrorType(res.status);
      const message = payload?.error?.message ?? `Request failed with status ${res.status}`;
      const retryable = RETRYABLE_STATUSES.has(res.status);

      if (!retryable || attempt >= maxRetries) {
        throw new ClaudeApiError(message, res.status, errorType, retryable);
      }

      const delay = baseDelayMs * 2 ** attempt + Math.random() * 200;
      await new Promise((resolve) => setTimeout(resolve, delay));
      attempt++;
    } catch (err) {
      if (err instanceof ClaudeApiError) throw err;

      // Network-level failure (timeout, DNS, connection reset)
      if (attempt >= maxRetries) {
        throw new ClaudeApiError(
          err instanceof Error ? err.message : "Network error",
          0,
          "network_error",
          true
        );
      }
      const delay = baseDelayMs * 2 ** attempt + Math.random() * 200;
      await new Promise((resolve) => setTimeout(resolve, delay));
      attempt++;
    }
  }
}

This gives you capped retries, exponential growth, and jitter to avoid thundering-herd retries when many requests hit a rate limit simultaneously.

Handling errors in streaming responses

Streaming adds a wrinkle: errors can arrive mid-stream as a message_delta or error event instead of an HTTP status. When reading a server-sent events stream, check each event type explicitly:

for await (const chunk of stream) {
  if (chunk.type === "error") {
    throw new ClaudeApiError(
      chunk.error.message,
      0,
      chunk.error.type,
      chunk.error.type === "overloaded_error"
    );
  }
  // handle normal content_block_delta events
}

Don't assume a successful 200 response means the entire stream will complete cleanly — overload errors can surface after the connection is already open.

Using this at the application layer

Once you have ClaudeApiError, your calling code can branch cleanly:

try {
  const result = await callClaudeWithRetry(url, body, apiKey);
  return result;
} catch (err) {
  if (err instanceof ClaudeApiError) {
    if (err.status === 401) {
      // alert on-call: key rotation needed
    }
    if (err.errorType === "rate_limit_error") {
      // queue job for later instead of failing the user request
    }
  }
  throw err;
}

This pattern — typed errors, retry classification, backoff with jitter, and explicit stream error checks — is exactly what you'd want whether you're calling Claude directly or through a gateway. If you'd rather not maintain this logic yourself, SubToAPI wraps Claude behind a standard HTTPS API with its own normalized error responses, so your TypeScript client only needs to handle one consistent error shape. See the messages docs and streaming docs for the exact response format, or start with the quickstart.

questions

Should I retry every failed Claude API request? No. Only retry errors that are transient — 429, 500, and 529 — plus network-level failures like timeouts. Client errors (400, 401, 403, 404) indicate a problem with the request itself and will fail identically on every retry.

What's a reasonable backoff strategy for 429 and 529 errors? Exponential backoff starting around 500ms, doubling each attempt, capped at 3-5 retries, with a small random jitter added to each delay. This avoids synchronized retry storms when multiple requests hit rate limits at once.

Does the error format differ between non-streaming and streaming requests? Yes. Non-streaming errors arrive as a standard HTTP error response with a JSON body. Streaming errors can also appear as an error event inside an otherwise-200 SSE stream, so your stream parser needs to check event types explicitly rather than relying on the initial HTTP status alone.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →