Principle:Openai Openai python API Error Handling
| Knowledge Sources | |
|---|---|
| Domains | Error_Handling, SDK_Infrastructure |
| Last Updated | 2026-02-15 00:00 GMT |
Overview
A hierarchical exception pattern that maps HTTP status codes and connection failures to typed Python exceptions for structured error recovery.
Description
API error handling provides a structured way to catch and respond to failures during API interactions. The exception hierarchy maps each HTTP status code to a specific exception class (e.g., 429 to RateLimitError, 401 to AuthenticationError), enabling granular try/except handling. Connection-level failures (timeouts, network errors) are mapped to separate exception types.
The SDK also provides automatic retry logic for transient errors (rate limits, server errors) with exponential backoff, reducing the need for manual retry code.
Usage
Use this principle to build resilient API integrations. Catch specific exceptions for differentiated handling: retry on RateLimitError, alert on AuthenticationError, log and retry on InternalServerError. The SDK handles most retries automatically via max_retries.
Theoretical Basis
The error hierarchy follows a Template Method pattern rooted in HTTP semantics:
# Exception hierarchy (abstract)
OpenAIError (base)
├── APIError (all API-related errors)
│ ├── APIConnectionError (network failure)
│ ├── APITimeoutError (request timeout)
│ └── APIStatusError (HTTP error response)
│ ├── BadRequestError (400)
│ ├── AuthenticationError (401)
│ ├── PermissionDeniedError (403)
│ ├── NotFoundError (404)
│ ├── ConflictError (409)
│ ├── UnprocessableEntityError (422)
│ ├── RateLimitError (429)
│ └── InternalServerError (>=500)
├── LengthFinishReasonError
└── ContentFilterFinishReasonError