Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Principle:Anthropics Anthropic sdk python Error Handling And Exceptions

From Leeroopedia
Knowledge Sources
Domains SDK Architecture, Error Handling
Last Updated 2026-02-15 00:00 GMT

Overview

The Error Handling And Exceptions principle defines how the Anthropic Python SDK maps HTTP status codes and connection failures to a hierarchy of typed Python exception classes. Rather than exposing raw HTTP responses or generic error types, the SDK provides a structured exception taxonomy rooted in APIError. APIStatusError subtypes correspond to specific HTTP 4xx/5xx status codes (e.g., AuthenticationError for 401, RateLimitError for 429), while APIConnectionError handles transport-level failures such as DNS resolution failures and connection timeouts. This allows callers to write granular except clauses that match the exact failure mode.

Theoretical Basis

Exception Hierarchy Design

The SDK defines a rooted exception hierarchy that enables both broad and narrow error handling:

APIError (base)
├── APIConnectionError          # Transport failures (no HTTP response)
├── APIStatusError              # Any HTTP error response
│   ├── BadRequestError         # 400
│   ├── AuthenticationError     # 401
│   ├── PermissionDeniedError   # 403
│   ├── NotFoundError           # 404
│   ├── ConflictError           # 409
│   ├── UnprocessableEntityError# 422
│   ├── RateLimitError          # 429
│   └── InternalServerError     # 500+
└── APIResponseValidationError  # Response failed Pydantic validation

This hierarchy follows the Liskov Substitution Principle: a caller who catches APIStatusError will also catch any of its subtypes, so code can be written at whatever level of specificity is appropriate. A retry loop might catch RateLimitError specifically to implement back-off, while a top-level handler catches APIError to log all SDK failures uniformly.

HTTP Status Code Mapping

Each APIStatusError subclass is bound to a specific HTTP status code range. When the SDK receives an HTTP response with a non-2xx status, it inspects the status code and instantiates the most specific exception class available. If no specific subclass matches, a generic APIStatusError is raised. This deterministic mapping means:

  • No parsing ambiguity -- The exception type unambiguously identifies the HTTP failure category.
  • IDE-friendly -- Type checkers can verify that the correct exception type is caught.
  • Forward-compatible -- New status-code-specific exceptions can be added without breaking existing except APIStatusError handlers.

Transport-Level vs. Application-Level Errors

The SDK distinguishes between two fundamentally different failure modes:

  • APIConnectionError -- The HTTP request never received a response. This covers DNS failures, TCP connection refused, TLS handshake errors, and read timeouts. The original exception is chained via Python's __cause__ mechanism for debugging.
  • APIStatusError -- The server returned a well-formed HTTP response with an error status code. The exception carries the parsed response body, status code, and headers.

This separation is critical for retry logic: connection errors are typically safe to retry immediately, while status errors like 400 (bad request) should not be retried without modifying the request.

Structured Error Bodies

When available, APIStatusError exceptions expose the parsed JSON error body through the body attribute. The Anthropic API returns error responses in a structured format:

{
  "type": "error",
  "error": {
    "type": "invalid_request_error",
    "message": "max_tokens: must be greater than 0"
  }
}

The SDK preserves this structure so that callers can programmatically inspect the error type and message without string parsing.

Response Validation Errors

APIResponseValidationError is raised when the HTTP response has a success status code (2xx) but the response body fails Pydantic model validation. This guards against API contract violations and is especially useful during API version transitions when response shapes may change.

Design Constraints

  • All SDK exceptions inherit from APIError, which itself inherits from Python's built-in Exception. This ensures compatibility with standard exception handling patterns.
  • APIConnectionError does not carry an HTTP status code because no response was received.
  • The message attribute on all exceptions provides a human-readable summary suitable for logging.
  • Retry logic in the base client catches APIConnectionError and specific APIStatusError subtypes (429, 5xx) for automatic retries with exponential back-off.

Related Pages

Implemented By

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment