Skip to content
mentoor

Topic 1 of 5 · 5 min read

Reading API error types and status codes

Goal: Classify an API error response as retryable or not and name the fix for each error that retrying will not solve.

Read the status code first: 4xx errors mean your request is wrong and retrying changes nothing, while 429, 5xx and overload errors mean try again later. Every provider returns an HTTP status and a JSON body with a type and a message. The type tells you what to fix.

Check yourself · 1 of 3

Your call returns HTTP 400 with an invalid_request_error body. What is the right response?

Choose one answer

Why it matters

A client that retries every failure wastes money and time on errors that can never succeed. A client that never retries drops requests on a blip. Sorting errors into "fix it" and "wait and retry" is the first job of any API client.

The common codes

Status Meaning Retry? Fix
400 Invalid request: bad JSON, missing field, wrong parameter No Fix the request body
401 Authentication: missing, wrong or revoked key No Check the key and the header it travels in
403 Permission: the key may not use this model or feature No Change the key's access or the model
404 Not found: unknown model name or resource No Correct the name
413 Payload too large: the request exceeds the byte limit No Shrink or split the input
429 Rate limit: you are over your quota Yes, after waiting Slow down, see the headers
500 Server error on the provider side Yes, with a cap Retry, then report with the request id
529 Overloaded: the provider is short of capacity Yes, with backoff Retry later or fall back

Claude uses 529 for overload. Other vendors may use 503 for the same thing. Check each vendor's list, because the same number is not always used the same way.

How to do it

  1. Log the status code, the error type, the message and the request id header on every failure.
  2. Branch on the status class: 4xx except 429 goes to the caller as a bug; 429 and 5xx go to the retry path.
  3. Map each non-retryable error to a named fix, so the message tells the next engineer what to change.

Before and after

# Before: retries everything, including a typo in the model name
for attempt in range(5):
    try:
        return client.messages.create(**params)
    except Exception:
        time.sleep(2)

This sleeps and retries a 404 five times, then raises a vague error. After:

import anthropic

try:
    return client.messages.create(**params)
except anthropic.BadRequestError as e:      # 400: fix the request
    raise ValueError(f"Bad request {e.response.headers.get('request-id')}: {e.message}")
except anthropic.AuthenticationError:       # 401: fix the key
    raise
except (anthropic.RateLimitError, anthropic.InternalServerError):
    schedule_retry(params)                  # 429 and 5xx: wait and retry

What goes wrong

  • Retrying a 400. The same bad request fails the same way each time and burns your rate limit.
  • Treating 429 as a bug. It is a pace signal, not a broken request.
  • Dropping the request id. Support cannot trace a failure without it.
  • Errors inside a stream. A stream can start with 200 and then fail partway, so the status code alone is not enough.

Examples

The typo that looked like an outage

A nightly job calls claude-sonet-4 (one n missing). The API returns 404 not found. The job's wrapper retries all errors 6 times with a 30 second pause, so a 3 minute stall hides a one-character typo. Branching on 404 fails the job at once with the message "unknown model".

A 413 on a long transcript

A support tool sends a full 400-message chat history plus attached logs and gets 413. Retrying sends the same bytes. The fix is to summarise older turns or trim the attachments before sending.

Key points

  • Status 400, 401, 403, 404 and 413 describe a problem in your request or key, so retrying cannot help.
  • 429, 5xx and overload errors are temporary and belong on a retry path with a cap.
  • Every non-retryable error has a named fix, such as the key, the model name or the input size.
  • Log the status, the error type, the message and the request id so support can trace the failure.
  • A streaming response can return 200 and still fail mid-stream, so handle error events too.

Common mistakes

  • Retrying every exception with the same delay, including 400 and 404 responses.
  • Showing users the raw provider message instead of what failed and what to do next.
  • Treating 401 as temporary and looping until the key is locked or the logs fill up.
  • Throwing away the request id header, so no failure can be traced later.

Check yourself · 2 of 3

Which of these statuses is the best candidate for an automatic retry after a wait?

Choose one answer

Check yourself · 3 of 3

A 401 error comes back from every call after a key rotation. What should the client do?

Choose one answer

Practice items, not counted towards your mastery.

Start here