Implementation:Anthropics Anthropic sdk python Exceptions
| Knowledge Sources | |
|---|---|
| Domains | Error_Handling, API_Client |
| Last Updated | 2026-02-15 12:00 GMT |
Overview
The _exceptions.py module defines the complete exception hierarchy for the Anthropic Python SDK, mapping HTTP status codes and connection failures to specific, catchable exception classes.
Description
The exception hierarchy is rooted at AnthropicError, which extends Python's built-in Exception. Below it, APIError adds a message, an httpx.Request reference, and an optional body containing the parsed API response (or raw response if JSON parsing fails, or None if no response was received).
The hierarchy branches into three main paths. APIConnectionError represents network-level failures (no HTTP response received), with APITimeoutError as a specialization for timeout/cancellation scenarios. APIStatusError represents HTTP 4xx/5xx responses and adds a response object, status_code, and request_id (extracted from the request-id response header). Each specific HTTP status code gets its own subclass with a fixed status_code literal. APIResponseValidationError handles cases where the API returns a successful response that fails schema validation.
This design allows callers to catch exceptions at any level of specificity: a broad except APIError handles all API issues, while except RateLimitError targets only 429 responses for retry logic.
Usage
Import exceptions from the top-level anthropic namespace and use them in try/except blocks around API calls. Catch specific exceptions for targeted error handling or broader base classes for general fallback behavior.
Code Reference
Source Location
- Repository: Anthropic SDK Python
- File:
src/anthropic/_exceptions.py
Signature
class AnthropicError(Exception):
pass
class APIError(AnthropicError):
message: str
request: httpx.Request
body: object | None
def __init__(self, message: str, request: httpx.Request, *, body: object | None) -> None: ...
class APIResponseValidationError(APIError):
response: httpx.Response
status_code: int
def __init__(self, response: httpx.Response, body: object | None, *, message: str | None = None) -> None: ...
class APIStatusError(APIError):
response: httpx.Response
status_code: int
request_id: str | None
def __init__(self, message: str, *, response: httpx.Response, body: object | None) -> None: ...
class APIConnectionError(APIError):
def __init__(self, *, message: str = "Connection error.", request: httpx.Request) -> None: ...
class APITimeoutError(APIConnectionError):
def __init__(self, request: httpx.Request) -> None: ...
class BadRequestError(APIStatusError): # 400
class AuthenticationError(APIStatusError): # 401
class PermissionDeniedError(APIStatusError): # 403
class NotFoundError(APIStatusError): # 404
class ConflictError(APIStatusError): # 409
class RequestTooLargeError(APIStatusError): # 413
class UnprocessableEntityError(APIStatusError): # 422
class RateLimitError(APIStatusError): # 429
class ServiceUnavailableError(APIStatusError): # 503
class DeadlineExceededError(APIStatusError): # 504
class OverloadedError(APIStatusError): # 529
class InternalServerError(APIStatusError): # 5xx (generic)
Import
from anthropic import (
AnthropicError,
APIError,
APIStatusError,
APITimeoutError,
APIConnectionError,
APIResponseValidationError,
BadRequestError,
AuthenticationError,
PermissionDeniedError,
NotFoundError,
ConflictError,
UnprocessableEntityError,
RateLimitError,
InternalServerError,
)
I/O Contract
Exception Hierarchy
Exception
+-- AnthropicError
+-- APIError
+-- APIResponseValidationError
+-- APIStatusError
| +-- BadRequestError (400)
| +-- AuthenticationError (401)
| +-- PermissionDeniedError (403)
| +-- NotFoundError (404)
| +-- ConflictError (409)
| +-- RequestTooLargeError (413)
| +-- UnprocessableEntityError (422)
| +-- RateLimitError (429)
| +-- ServiceUnavailableError (503)
| +-- DeadlineExceededError (504)
| +-- OverloadedError (529)
| +-- InternalServerError (5xx)
+-- APIConnectionError
+-- APITimeoutError
Exception Attributes
| Exception Class | Attribute | Type | Description |
|---|---|---|---|
APIError |
message |
str |
Human-readable error message |
APIError |
request |
httpx.Request |
The outgoing HTTP request that caused the error |
APIError |
body |
None | Parsed JSON response body, raw response, or None
|
APIStatusError |
response |
httpx.Response |
The full HTTP response object |
APIStatusError |
status_code |
int |
HTTP status code (e.g. 400, 401, 429) |
APIStatusError |
request_id |
None | Value of the request-id response header
|
APIResponseValidationError |
response |
httpx.Response |
The HTTP response that failed validation |
APIResponseValidationError |
status_code |
int |
HTTP status code of the response |
HTTP Status Code Mapping
| Status Code | Exception Class | Typical Cause |
|---|---|---|
| 400 | BadRequestError |
Malformed request or invalid parameters |
| 401 | AuthenticationError |
Missing or invalid API key |
| 403 | PermissionDeniedError |
Insufficient permissions for the requested resource |
| 404 | NotFoundError |
Requested resource does not exist |
| 409 | ConflictError |
Resource state conflict |
| 413 | RequestTooLargeError |
Request payload exceeds size limits |
| 422 | UnprocessableEntityError |
Semantically invalid request |
| 429 | RateLimitError |
Rate limit exceeded; back off and retry |
| 503 | ServiceUnavailableError |
Service temporarily unavailable |
| 504 | DeadlineExceededError |
Server-side deadline exceeded |
| 529 | OverloadedError |
API is overloaded |
Usage Examples
import anthropic
client = anthropic.Anthropic()
# Catch specific errors
try:
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}],
)
except anthropic.AuthenticationError as e:
print(f"Authentication failed: {e.message}")
print(f"Request ID: {e.request_id}")
except anthropic.RateLimitError as e:
print(f"Rate limited (status {e.status_code}): {e.message}")
# Implement exponential backoff
except anthropic.APITimeoutError:
print("Request timed out")
except anthropic.APIConnectionError:
print("Network connection failed")
except anthropic.APIStatusError as e:
print(f"API returned status {e.status_code}: {e.message}")
print(f"Response body: {e.body}")
except anthropic.APIError as e:
print(f"Unexpected API error: {e.message}")
Related Pages
Related Implementations
- Implementation:Anthropics_Anthropic_sdk_python_Package_Init -- Re-exports all exception classes
- Implementation:Anthropics_Anthropic_sdk_python_Anthropic_Client_Init -- Client that raises these exceptions