Error Handling
AI APIs can fail for many reasons: invalid API key, rate limits, network issues, or content policy violations. Proper error handling makes your application robust and gives users helpful feedback.
10 min•By Priygop Team•Updated 2026
Common AI API Errors and How to Handle Them
Common AI API Errors and How to Handle Them
# Comprehensive error handling for AI API calls
import os
from openai import OpenAI, AuthenticationError, RateLimitError, APIConnectionError, BadRequestError
def ask_ai_with_error_handling(question, system=None):
"""
Call the OpenAI API with comprehensive error handling.
"""
api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
return {"success": False, "error": "API key not configured. Contact support.", "code": "no_key"}
client = OpenAI(api_key=api_key)
messages = []
if system:
messages.append({"role": "system", "content": system})
messages.append({"role": "user", "content": question})
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
max_tokens=300,
)
return {
"success": True,
"text": response.choices[0].message.content,
"tokens_used": response.usage.total_tokens
}
except AuthenticationError:
# 401: wrong or expired API key
return {"success": False, "error": "Authentication failed. Check your API key.", "code": "auth_error"}
except RateLimitError:
# 429: too many requests or quota exceeded
return {"success": False, "error": "Rate limit reached. Please wait a moment.", "code": "rate_limit"}
except APIConnectionError:
# Network issue: cannot reach the API
return {"success": False, "error": "Could not connect to AI service. Check your internet connection.", "code": "connection_error"}
except BadRequestError as e:
# 400: invalid request (content policy, token limit, etc.)
return {"success": False, "error": f"Request was invalid: {str(e)}", "code": "bad_request"}
except Exception as e:
# Catch-all for unexpected errors
return {"success": False, "error": "An unexpected error occurred. Please try again.", "code": "unknown"}
# Test the function
result = ask_ai_with_error_handling("What is an API key?")
if result["success"]:
print(f"Success: {result['text'][:100]}...")
print(f"Tokens used: {result['tokens_used']}")
else:
print(f"Error ({result['code']}): {result['error']}")Diagram
Loading diagram…
Never swallow errors silently. Log, report, recover gracefully.