If you want to handle multiple OpenAI API exceptions in a single block while logging the error, you can catch a tuple of exception types:
import logging
from openai import OpenAI
from openai import APIConnectionError, APITimeoutError, RateLimitError
client = OpenAI()
try:
response = client.responses.create(
model="gpt-4.1-mini",
input="Summarize this text..."
)
except (RateLimitError, APITimeoutError, APIConnectionError) as e:
logging.exception("OpenAI API error: %s", e)
Using logging.exception() is generally preferable inside an except block because it logs both the error message and the full traceback.
If you want to catch all OpenAI SDK exceptions, catch the base exception class:
import logging
from openai import OpenAI, OpenAIError
client = OpenAI()
try:
response = client.responses.create(
model="gpt-4.1-mini",
input="Summarize this text..."
)
except OpenAIError as e:
logging.exception("OpenAI API error: %s", e)
This will catch errors such as:
RateLimitError
APITimeoutError
APIConnectionError
AuthenticationError
PermissionDeniedError
NotFoundError
ConflictError
UnprocessableEntityError
InternalServerError
- and other SDK-specific exceptions
If you're using the older 0.x OpenAI Python library (which uses openai.error.Timeout and openai.error.RateLimitError), the equivalent pattern is:
import logging
import openai
try:
# OpenAI API call
pass
except openai.error.OpenAIError as e:
logging.exception("OpenAI API error: %s", e)
Catching openai.error.OpenAIError handles all exceptions derived from the old SDK's base exception class, including Timeout, RateLimitError, APIError, APIConnectionError, and others.