Docs
Error Handling

Error Handling

Understanding and handling API errors.

Error Handling

This guide covers the error responses you may encounter and how to handle them.

Error Response Format

All errors follow this structure:

{
  "error": "Human-readable error message",
  "code": "ERROR_CODE",
  "details": { }
}
  • error - A human-readable description of the error
  • code - A machine-readable error code (optional)
  • details - Additional context about the error (optional)

HTTP Status Codes

400 Bad Request

Invalid input or parameters.

{
  "error": "Prompt is required",
  "code": "VALIDATION_ERROR"
}

Common causes:

  • Missing required fields
  • Invalid field values or types
  • Malformed JSON

Solution: Check your request body and ensure all required fields are present with valid values.

401 Unauthorized

Authentication failed.

{
  "error": "API key not found or expired",
  "code": "AUTHENTICATION_ERROR"
}

Common causes:

  • Missing Authorization header
  • Invalid or expired API key
  • Incorrect header format (should be Bearer <key>)

Solution: Verify your API key is correct and not expired. Check the header format.

402 Payment Required

Insufficient credits for the operation.

{
  "error": "Insufficient credits",
  "creditsRemaining": 0
}

Common causes:

  • No credits remaining
  • Operation requires more credits than available

Solution: Purchase additional credits or upgrade your subscription.

403 Forbidden

Operation not allowed.

{
  "error": "Style limit reached (5)",
  "code": "QUOTA_EXCEEDED"
}

Common causes:

  • Tier-based limit reached (styles, brands, etc.)
  • Attempting to access another organization's resources

Solution: Upgrade your subscription for higher limits.

404 Not Found

Resource doesn't exist.

{
  "error": "Thumbnail not found",
  "code": "NOT_FOUND"
}

Common causes:

  • Resource was deleted
  • Invalid ID format
  • Resource belongs to different organization

Solution: Verify the resource ID is correct.

429 Too Many Requests

Rate limit exceeded.

{
  "error": "Rate limit exceeded",
  "retryAfter": 45
}

Headers:

  • Retry-After: 45 - Seconds until you can retry

Solution: Wait for the rate limit window to reset. Consider spreading requests over time.

500 Internal Server Error

Something went wrong on our end.

{
  "error": "Internal server error",
  "code": "INTERNAL_ERROR"
}

Solution: Retry the request. If the issue persists, contact support.

Handling Errors in Code

JavaScript

async function apiRequest(endpoint, options = {}) {
  const response = await fetch(`${BASE_URL}${endpoint}`, {
    ...options,
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json',
      ...options.headers
    }
  });
 
  const data = await response.json();
 
  if (!response.ok) {
    switch (response.status) {
      case 401:
        throw new Error('Invalid API key');
      case 402:
        throw new Error(`Insufficient credits (${data.creditsRemaining} remaining)`);
      case 429:
        const retryAfter = response.headers.get('Retry-After') || data.retryAfter;
        throw new Error(`Rate limited. Retry after ${retryAfter} seconds`);
      default:
        throw new Error(data.error || 'Unknown error');
    }
  }
 
  return data;
}

Python

import requests
 
class APIError(Exception):
    def __init__(self, message, status_code, details=None):
        self.message = message
        self.status_code = status_code
        self.details = details
        super().__init__(message)
 
def api_request(endpoint, method='GET', data=None):
    response = requests.request(
        method,
        f'{BASE_URL}{endpoint}',
        headers={
            'Authorization': f'Bearer {API_KEY}',
            'Content-Type': 'application/json'
        },
        json=data
    )
 
    result = response.json()
 
    if not response.ok:
        if response.status_code == 401:
            raise APIError('Invalid API key', 401)
        elif response.status_code == 402:
            raise APIError(
                f"Insufficient credits ({result.get('creditsRemaining', 0)} remaining)",
                402
            )
        elif response.status_code == 429:
            retry_after = result.get('retryAfter', 60)
            raise APIError(f'Rate limited. Retry after {retry_after}s', 429)
        else:
            raise APIError(result.get('error', 'Unknown error'), response.status_code)
 
    return result

Best Practices

  1. Always handle errors gracefully - Don't assume requests will succeed
  2. Implement exponential backoff - For rate limits and server errors
  3. Log errors for debugging - Include request details and error responses
  4. Show user-friendly messages - Translate error codes to helpful messages
  5. Check credits before operations - Avoid failed requests due to insufficient credits