How to Handle Claude API Errors in Python
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
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>
| Class | When it's raised |
|---|---|
AuthenticationError | 401: the key is wrong, revoked or expired |
NotFoundError | 404: for example, a model ID that doesn't exist |
RateLimitError | 429: a rate limit or spend limit was hit |
APIStatusError | Any error response; the classes above are kinds of it |
APIConnectionError | No 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
.envfile asANTHROPIC_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
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 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
uv run --env-file .env errors.py
AuthenticationError, status 401: Invalid bearer token
NotFoundError, status 404: model: claude-opus-9-9
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
| Mistake | What happens | Do this instead |
|---|---|---|
Putting APIStatusError before a narrower class | The narrower except never runs | List narrower classes first |
| Retrying every error yourself | A wrong key or model fails the same way every time, on top of the SDK's own retries | Retry 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 problems | Catch the SDK's classes |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
AuthenticationError, status 401 | The key is wrong, revoked or not loaded | Check ANTHROPIC_API_KEY |
NotFoundError naming the model | A misspelled or retired model ID | Use an ID from the models overview |
RateLimitError, status 429 | Too many requests, or a spend limit reached | Wait 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
- Errors — status codes, SDK classes and retry behaviour.
- Anthropic Python SDK — error handling and client options.
