API Error Handling
API errors are normal. Networks fail. Services go down. Rate limits are hit. A well-designed agent handles these gracefully and continues working rather than crashing.
8 min•By Priygop Team•Updated 2026
Error Handling Strategy
Error Handling Strategy
import time
import requests
class APIClient:
"""API client with comprehensive error handling for agent tools."""
def __init__(self, base_url: str, api_key: str):
self.base_url = base_url
self.headers = {"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"}
def get(self, path: str, params: dict = None) -> dict:
url = f"{self.base_url}{path}"
try:
response = requests.get(url, params=params,
headers=self.headers, timeout=15)
# Success
if response.status_code in (200, 201, 204):
body = response.json() if response.text else {}
return {"status": "success", "data": body}
# Client errors (4xx) — do not retry
if 400 <= response.status_code < 500:
error_body = {}
try:
error_body = response.json()
except Exception:
pass
return {
"status": "error",
"error_type": "client",
"http_status": response.status_code,
"error": error_body.get("message", response.text[:200])
}
# Server errors (5xx) — can retry
return {
"status": "error",
"error_type": "server",
"http_status": response.status_code,
"error": f"Server error {response.status_code}"
}
except requests.Timeout:
return {"status": "error", "error_type": "timeout",
"error": "Request timed out after 15 seconds"}
except requests.ConnectionError:
return {"status": "error", "error_type": "network",
"error": "Cannot connect to API"}
client = APIClient("https://api.example.com", "your-key")
result = client.get("/orders", params={"status": "pending"})
print("Result status:", result["status"])