Skip to main content
coding intermediate

Handle API Error Responses

Generate robust error handling code for API responses. Create comprehensive error management for REST APIs with retry logic and user feedback.

Works with: chatgptclaudegemini

Prompt Template

You are an expert API developer. Create comprehensive error handling code for API responses in [PROGRAMMING_LANGUAGE]. The solution should handle the following requirements: **API Context:** - API endpoint: [API_ENDPOINT] - Expected response format: [RESPONSE_FORMAT] - Authentication method: [AUTH_METHOD] **Error Handling Requirements:** 1. Handle HTTP status codes (400, 401, 403, 404, 429, 500, 502, 503, 504) 2. Implement exponential backoff retry logic for retryable errors 3. Parse and extract meaningful error messages from API responses 4. Log errors appropriately with different severity levels 5. Provide user-friendly error messages 6. Handle network timeouts and connection failures 7. Implement circuit breaker pattern if specified: [CIRCUIT_BREAKER_NEEDED] **Additional Specifications:** - Maximum retry attempts: [MAX_RETRIES] - Initial retry delay: [INITIAL_DELAY] seconds - Timeout duration: [TIMEOUT] seconds - Logging framework: [LOGGING_FRAMEWORK] **Output Requirements:** - Complete, production-ready code with proper error classes/types - Inline comments explaining error handling logic - Example usage demonstrating different error scenarios - Unit test examples for critical error paths - Configuration options for retry behavior Ensure the code is maintainable, follows best practices for the specified language, and provides clear separation between different types of errors (client errors, server errors, network errors).

Variables to Customize

[PROGRAMMING_LANGUAGE]

The programming language to use for the error handling implementation

Example: Python

[API_ENDPOINT]

The specific API endpoint being called

Example: https://api.example.com/v1/users

[RESPONSE_FORMAT]

Expected API response format

Example: JSON

[AUTH_METHOD]

Authentication method used by the API

Example: Bearer Token

[CIRCUIT_BREAKER_NEEDED]

Whether to implement circuit breaker pattern

Example: Yes

[MAX_RETRIES]

Maximum number of retry attempts

Example: 3

[INITIAL_DELAY]

Initial delay before first retry in seconds

Example: 1

[TIMEOUT]

Request timeout duration in seconds

Example: 30

[LOGGING_FRAMEWORK]

Preferred logging framework or method

Example: Python logging module

Example Output

```python import requests import time import logging from enum import Enum from typing import Optional, Dict, Any class APIErrorType(Enum): CLIENT_ERROR = "client_error" SERVER_ERROR = "server_error" NETWORK_ERROR = "network_error" RATE_LIMIT = "rate_limit" AUTHENTICATION = "authentication" class APIException(Exception): def __init__(self, message: str, error_type: APIErrorType, status_code: Optional[int] = None): self.message = message self.error_type = error_type self.status_code = status_code super().__init__(self.message) class APIClient: def __init__(self, base_url: str, auth_token: str, max_retries: int = 3): self.base_url = base_url self.auth_token = auth_token self.max_retries = max_retries self.logger = logging.getLogger(__name__) def _make_request(self, endpoint: str) -> Dict[Any, Any]: url = f"{self.base_url}{endpoint}" headers = {"Authorization": f"Bearer {self.auth_token}"} for attempt in range(self.max_retries + 1): try: response = requests.get(url, headers=headers, timeout=30) if response.status_code == 200: return response.json() elif response.status_code == 429: if attempt < self.max_retries: delay = (2 ** attempt) * 1 # Exponential backoff self.logger.warning(f"Rate limited. Retrying in {delay}s") time.sleep(delay) continue raise APIException("Rate limit exceeded", APIErrorType.RATE_LIMIT, 429) elif response.status_code == 401: raise APIException("Authentication failed", APIErrorType.AUTHENTICATION, 401) elif 400 <= response.status_code < 500: raise APIException(f"Client error: {response.text}", APIErrorType.CLIENT_ERROR, response.status_code) else: raise APIException(f"Server error: {response.text}", APIErrorType.SERVER_ERROR, response.status_code) except requests.RequestException as e: if attempt < self.max_retries: delay = (2 ** attempt) * 1 self.logger.error(f"Network error on attempt {attempt + 1}: {e}") time.sleep(delay) continue raise APIException(f"Network error: {str(e)}", APIErrorType.NETWORK_ERROR) ```

Pro Tips for Best Results

  • Always distinguish between retryable errors (5xx, network issues) and non-retryable errors (4xx client errors)
  • Implement exponential backoff with jitter to avoid thundering herd problems when multiple clients retry simultaneously
  • Log error details at appropriate levels - DEBUG for retries, ERROR for final failures, CRITICAL for authentication issues
  • Consider implementing a circuit breaker pattern for frequently failing APIs to prevent cascade failures
  • Parse API error response bodies to extract specific error messages when available, don't just rely on HTTP status codes

Tags

Want 500+ Expert Prompts?

Get the Premium Prompt Pack — organized, tested, and ready to use.

Get it for $29

Related Prompts You Might Like