API Codex
API Guides

Error Handling Guide

Proper error handling is crucial for building reliable applications. This guide covers all error scenarios you might encounter when using API Codex APIs and how to handle them effectively.

Error Response Format

All API Codex APIs return consistent error responses:

jsonCode
{ "error": "Error type or code", "message": "Human-readable error description", "details": "Additional context about the error", "timestamp": "2024-01-15T10:30:00Z" }

HTTP Status Codes

Success Codes (2xx)

CodeStatusDescription
200OKRequest successful
201CreatedResource created successfully
202AcceptedRequest accepted for processing
204No ContentRequest successful, no content to return

Client Error Codes (4xx)

CodeStatusDescriptionCommon Causes
400Bad RequestInvalid request parametersMissing required fields, invalid data types
401UnauthorizedAuthentication failedInvalid or missing API key
403ForbiddenAccess deniedSubscription expired, insufficient permissions
404Not FoundResource not foundInvalid endpoint, deleted resource
405Method Not AllowedHTTP method not supportedUsing POST on GET-only endpoint
422Unprocessable EntityRequest validation failedInvalid email format, domain doesn't exist
429Too Many RequestsRate limit exceededToo many requests in time window

Server Error Codes (5xx)

CodeStatusDescriptionAction Required
500Internal Server ErrorServer-side errorRetry with exponential backoff
502Bad GatewayInvalid upstream responseRetry after brief delay
503Service UnavailableService temporarily downCheck status page, retry later
504Gateway TimeoutRequest timeoutRetry with smaller payload

Common Error Scenarios

Authentication Errors

Invalid API Key

jsonCode
{ "error": "INVALID_API_KEY", "message": "The provided API key is invalid", "statusCode": 401 }

Solution: Verify your API key is correct (no extra spaces), check if the key is active in RapidAPI dashboard, and ensure your subscription is active.

Expired Subscription

jsonCode
{ "error": "SUBSCRIPTION_EXPIRED", "message": "Your subscription has expired", "statusCode": 403 }

Solution: Renew your subscription at RapidAPI. Consider implementing fallback to cached data when subscription issues occur.

Validation Errors

Missing Required Parameters

jsonCode
{ "error": "MISSING_PARAMETER", "message": "Required parameter 'domain' is missing", "statusCode": 400 }

Solution: Always validate required parameters before making API calls. Check the API documentation for required fields.

Invalid Data Format

jsonCode
{ "error": "INVALID_FORMAT", "message": "Invalid email format: 'not-an-email'", "statusCode": 422 }

Solution: Validate data format before making API calls:

  • Email: Use regex ^[^\s@]+@[^\s@]+\.[^\s@]+$
  • Domain: Ensure it's a valid domain format
  • IP Address: Validate IPv4 or IPv6 format

Rate Limiting Errors

See our comprehensive Rate Limiting Guide for detailed handling strategies.

Implementing Error Handling

A robust error handler should:

  1. Retry on transient errors (5xx, 429) with exponential backoff
  2. Fail fast on client errors (4xx except 429)
  3. Log all errors for debugging and monitoring
  4. Parse error responses to provide meaningful messages
javascriptCode
async function makeRequestWithRetry(requestFn, maxRetries = 3) { for (let attempt = 0; attempt < maxRetries; attempt++) { try { const response = await requestFn(); if (response.ok) return response; // Retry on 5xx or 429 if (response.status >= 500 || response.status === 429) { await sleep(1000 * Math.pow(2, attempt)); // Exponential backoff continue; } throw new Error(`API Error: ${response.status}`); } catch (error) { if (attempt === maxRetries - 1) throw error; } } }

Error Recovery Strategies

1. Graceful Degradation

When an API call fails, fall back gracefully:

  1. Return cached data if available
  2. Return default/fallback data for non-critical features
  3. Show user-friendly error instead of crashing

2. Circuit Breaker Pattern

Prevent cascading failures by "opening the circuit" after repeated failures:

  • CLOSED: Normal operation, requests pass through
  • OPEN: Too many failures, reject requests immediately for a timeout period
  • HALF-OPEN: After timeout, allow one test request to determine recovery

3. Retry with Jitter

Add randomness to retry delays to prevent thundering herd:

javascriptCode
const delay = baseDelay * Math.pow(2, attempt); // Exponential backoff const jitter = delay * 0.3 * (Math.random() * 2 - 1); // ±30% jitter await sleep(delay + jitter);

Error Monitoring

For production applications, integrate with error monitoring services:

  • Sentry - Real-time error tracking
  • LogRocket - Session replay with errors
  • DataDog - APM and error monitoring
  • Custom webhooks - Send errors to Slack, PagerDuty, etc.

Track metrics like:

  • Total errors by status code
  • Error rate over time
  • Most frequent error types
  • Time to detection and resolution

Best Practices

Do's ✅

  1. Always validate input before making API calls
  2. Implement retry logic with exponential backoff
  3. Log all errors for debugging and monitoring
  4. Use circuit breakers to prevent cascade failures
  5. Provide meaningful error messages to users
  6. Cache successful responses for fallback
  7. Monitor error rates and set up alerts

Don'ts ❌

  1. Don't ignore errors - Always handle them
  2. Don't retry infinitely - Set reasonable limits
  3. Don't expose sensitive information in error messages
  4. Don't retry non-retryable errors (4xx except 429)
  5. Don't break on non-critical errors - Degrade gracefully

Next Steps

Last modified on