Skip to main content

How to Handle Claude API Errors in Python

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

Calls to the Claude API can fail for reasons your code can fix, such as a wrong key or a misspelled model, and for reasons it can only wait out, such as a busy API. The Anthropic SDK raises a different exception class for each, so you can react to each one properly. This guide causes three failures on purpose and catches them, with real output from anthropic 2.14.0.

Syntax​

Syntax
import anthropic

try:
<client.messages.create(...)>
except anthropic.<NarrowerError>:
<handle that case>
except anthropic.APIStatusError as error:
<every other error response: error.status_code, error.message>
except anthropic.APIConnectionError:
<the API couldn't be reached>
ClassWhen it's raised
AuthenticationError401: the key is wrong, revoked or expired
NotFoundError404: for example, a model ID that doesn't exist
RateLimitError429: a rate limit or spend limit was hit
APIStatusErrorAny error response; the classes above are kinds of it
APIConnectionErrorNo response at all, such as no network

Anthropic's errors page maps each HTTP status to its SDK class and notes: "A class also catches its subclasses, so put the narrower class first." It also says the SDK "retries a failed request up to two times (three attempts in all)", for connection errors, timeouts, and the statuses 408, 409, 429 and 500 and above.

What It Costs​

The Claude API is paid, but failed requests like these produce no tokens: none of the three calls in this guide was billed.

Prerequisites​

  • A Claude API key, in a .env file as ANTHROPIC_API_KEY=....
  • The Anthropic Python SDK in a uv project. This guide uses anthropic 2.14.0, added with uv add anthropic, on Python 3.15.2.

Step 1: Write the Script​

errors.py
import anthropic


def ask(client, model):
try:
client.messages.create(
model=model,
max_tokens=100,
messages=[{"role": "user", "content": "Hi"}],
)
print("OK")
except anthropic.APIConnectionError as error:
print(f"{type(error).__name__}: {error.message}")
except anthropic.APIStatusError as error:
print(f"{type(error).__name__}, status {error.status_code}: {error.body['error']['message']}")


ask(anthropic.Anthropic(api_key="not-a-real-key"), "claude-opus-5-5")
ask(anthropic.Anthropic(), "claude-opus-9-9")
ask(anthropic.Anthropic(base_url="http://127.0.0.1:9", max_retries=0), "claude-opus-5-5")

The errors.py script in a macOS-style code window: ask() catches APIConnectionError and APIStatusError and prints the class name, status and message; it's called with a fake key, a model that doesn't exist, and an address where nothing listens.

The three calls break one thing each: a fake key, a model that doesn't exist, and an address on your own computer where nothing listens. max_retries=0 turns off the SDK's retries for the last one, so it fails at once.

Step 2: Run It​

Terminal
uv run --env-file .env errors.py
Output
AuthenticationError, status 401: Invalid bearer token
NotFoundError, status 404: model: claude-opus-9-9
APIConnectionError: Connection error.

The output in a terminal: AuthenticationError with status 401 and Invalid bearer token, NotFoundError with status 404 naming claude-opus-9-9, and APIConnectionError: Connection error.

One except anthropic.APIStatusError caught both error responses, and type(error).__name__ shows they arrived as the narrower AuthenticationError and NotFoundError. The connection failure has no status code, because no response came back. The 401 says "bearer token" because anthropic 2.14.0 sends the key in an Authorization: Bearer header.

Common Mistakes​

MistakeWhat happensDo this instead
Putting APIStatusError before a narrower classThe narrower except never runsList narrower classes first
Retrying every error yourselfA wrong key or model fails the same way every time, on top of the SDK's own retriesRetry only temporary errors such as 429 and 529, or let the SDK do it
Catching with a bare except:Bugs in your own code look like API problemsCatch the SDK's classes

Troubleshooting​

SymptomLikely causeFix
AuthenticationError, status 401The key is wrong, revoked or not loadedCheck ANTHROPIC_API_KEY
NotFoundError naming the modelA misspelled or retired model IDUse an ID from the models overview
RateLimitError, status 429Too many requests, or a spend limit reachedWait and retry, or check limits in the Console

FAQ​

Should I log the request ID?​

Yes. error.request_id identifies the request if you contact Anthropic's support. Keep it out of messages shown to users.

How do I change the number of retries?​

Pass max_retries to the client, as in anthropic.Anthropic(max_retries=5); 0 turns retries off.

Conclusion​

The fake key raised AuthenticationError (401), the made-up model NotFoundError (404), and the unreachable address APIConnectionError. APIStatusError caught the first two in one place.

Additional Resources​