Error Handling

Comprehensive guide to API error codes, common issues, and troubleshooting strategies. Build robust applications with proper error handling.

Error Categories

Client Errors (4xx)

Errors caused by invalid requests or authentication issues

Server Errors (5xx)

Temporary server-side issues and service unavailability

Rate Limit Errors

Usage limits exceeded, requires backoff and retry

Common Error Codes

400

Bad Request

Invalid request format, missing parameters, or malformed JSON

Common Causes

Missing required "prompt" parameter
Invalid JSON syntax in request body
Parameter value outside acceptable range

Solutions

Validate JSON format before sending
Check all required parameters are included
Verify parameter types match API specification
401

Unauthorized

Missing, invalid, or expired authentication credentials

Common Causes

No Authorization header provided
Invalid API key format
Expired JWT token

Solutions

Include valid Authorization header
Check API key starts with "sk-fusion-"
Refresh expired JWT tokens
403

Forbidden

Valid authentication but insufficient permissions

Common Causes

API key lacks required permissions
Account suspended or deactivated
Feature not available on current plan

Solutions

Upgrade account plan if needed
Contact support for permission issues
Check account status in dashboard
404

Not Found

Requested endpoint or resource does not exist

Common Causes

Incorrect API endpoint URL
Typo in endpoint path
Deprecated endpoint version

Solutions

Verify endpoint URL matches documentation
Check for typos in the request path
Use current API version endpoints
413

Payload Too Large

Request body exceeds maximum allowed size

Common Causes

Prompt text exceeds 100,000 characters
Uploaded file larger than 20MB
Too many files in single request

Solutions

Reduce prompt length or split into chunks
Compress or resize large files
Send files in separate requests
422

Unprocessable Entity

Request is valid but contains semantic errors

Common Causes

Parameter values outside valid ranges
Conflicting parameter combinations
Invalid file format or encoding

Solutions

Check parameter constraints in documentation
Validate parameter combinations
Use supported file formats only
429

Too Many Requests

Rate limit exceeded, requests are being throttled

Common Causes

Exceeded requests per minute limit
Concurrent request limit reached
Token usage rate limit hit

Solutions

Implement exponential backoff
Check rate limit headers
Upgrade plan for higher limits
500

Internal Server Error

Unexpected server-side error occurred

Common Causes

Database connection failure
Model processing error
Unexpected system exception

Solutions

Retry request after brief delay
Check service status page
Contact support with request ID
502

Bad Gateway

Error from upstream AI provider service

Common Causes

AI provider service unavailable
Timeout from provider API
Provider API rate limit reached

Solutions

Retry with different provider
Use NeuroSwitch for automatic failover
Check provider status pages
503

Service Unavailable

Service temporarily unavailable or under maintenance

Common Causes

Scheduled maintenance window
Service overload or capacity issues
Database maintenance

Solutions

Wait and retry after delay
Check service announcements
Implement retry with backoff

Error Response Format

Standard Error Response

{
  "error": {
    "type": "invalid_request",
    "message": "The prompt parameter is required",
    "code": 400
  },
  "request_id": "req_abc123def456",
  "timestamp": "2024-01-01T12:00:00Z"
}

Detailed Error Response

{
  "error": {
    "type": "validation_error",
    "message": "Parameter validation failed",
    "code": 422,
    "details": {
      "field": "temperature",
      "issue": "Value 3.5 exceeds maximum of 2.0"
    }
  },
  "request_id": "req_def456ghi789",
  "timestamp": "2024-01-01T12:00:00Z"
}

Rate Limiting & Retry Logic

Rate Limit Headers

X-RateLimit-Limit: 1000          // Requests per hour
X-RateLimit-Remaining: 842        // Remaining requests
X-RateLimit-Reset: 1704063600     // Reset timestamp
X-RateLimit-Retry-After: 3600     // Seconds until reset

Exponential Backoff Implementation

JavaScript Example

async function makeRequestWithRetry(data, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch('/api/chat', {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer sk-fusion-...',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      });

      if (response.status === 429) {
        const retryAfter = response.headers.get('Retry-After');
        const delay = retryAfter ? 
          parseInt(retryAfter) * 1000 : 
          Math.pow(2, i) * 1000;
        
        await new Promise(resolve => 
          setTimeout(resolve, delay)
        );
        continue;
      }

      return response;
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      await new Promise(resolve => 
        setTimeout(resolve, Math.pow(2, i) * 1000)
      );
    }
  }
}

Python Example

import time
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

def create_session_with_retries():
    session = requests.Session()
    
    retry_strategy = Retry(
        total=3,
        status_forcelist=[429, 500, 502, 503, 504],
        backoff_factor=1
    )
    
    adapter = HTTPAdapter(max_retries=retry_strategy)
    session.mount("http://", adapter)
    session.mount("https://", adapter)
    
    return session

# Usage
session = create_session_with_retries()
response = session.post(
    'https://api.mcp4.ai/chat',
    headers={'Authorization': 'Bearer sk-fusion-...'},
    json={'prompt': 'Hello world'}
)

Error Handling Best Practices

✅ Recommended Approaches

Log request_id for all errors
Implement exponential backoff for retries
Parse error details for specific handling
Monitor rate limit headers
Provide meaningful error messages to users

❌ Common Mistakes

Retrying immediately without delay
Ignoring HTTP status codes
Not handling rate limits properly
Exposing sensitive error details to users
Infinite retry loops

Debugging & Troubleshooting

Request Debugging

Log full request and response
Validate JSON syntax
Check Content-Type headers

Authentication Issues

Verify API key format
Check Authorization header
Test with cURL first

Performance Issues

Monitor response times
Check rate limit headers
Use request_id for support

Related Resources