DocsRouterDocsRouter
Api

Errors

Understanding API error codes and how to handle them

Errors

The DocsRouter API uses standard HTTP status codes to indicate the success or failure of your API requests. This guide covers all error types, their meanings, and how to handle them in your application.

Error Response Format

All errors follow a consistent JSON structure compatible with the OpenAI error format:

{
  "error": {
    "type": "invalid_request_error",
    "code": "validation_error",
    "message": "The 'url' parameter must be a valid URL.",
    "param": "url",
    "request_id": "req_abc123xyz"
  }
}

Error Object Fields

FieldTypeDescription
typestringThe category of error (see Error Types below)
codestringA specific error code for programmatic handling
messagestringA human-readable description of the error
paramstringThe parameter that caused the error (if applicable)
request_idstringUnique identifier for the request (useful for support)

HTTP Status Codes

CodeNameDescriptionRetry?
200OKRequest successfulN/A
400Bad RequestInvalid parameters or malformed requestNo
401UnauthorizedMissing or invalid API keyNo
402Payment RequiredInsufficient credits in accountNo*
403ForbiddenAPI key lacks required permissionsNo
404Not FoundEndpoint or model does not existNo
413Payload Too LargeRequest body exceeds size limitNo
422Unprocessable EntityValid JSON but semantic errorsNo
429Too Many RequestsRate limit exceededYes
500Internal Server ErrorUnexpected server errorYes
502Bad GatewayUpstream provider unavailableYes
503Service UnavailableDocsRouter temporarily unavailableYes
504Gateway TimeoutRequest timed outYes

* Retry after adding credits to your account

Error Types

authentication_error

Issues with your API key or account authentication.

Common causes:

  • Missing Authorization header
  • Invalid or revoked API key
  • Expired API key
  • Malformed Bearer token

Example:

{
  "error": {
    "type": "authentication_error",
    "code": "invalid_api_key",
    "message": "The API key provided is invalid or has been revoked."
  }
}

Solution: Check that your API key is correct and hasn't been revoked in the dashboard.

invalid_request_error

Issues with the request parameters or format.

Common causes:

  • Missing required fields
  • Invalid field values or types
  • Malformed JSON
  • Invalid image URL or base64 data

Example:

{
  "error": {
    "type": "invalid_request_error",
    "code": "missing_image",
    "message": "No images found in messages. Include at least one image_url or file.",
    "param": "messages"
  }
}

Solution: Review the API documentation and ensure all required fields are present with valid values.

insufficient_credits_error

Your account balance is too low to process the request.

Example:

{
  "error": {
    "type": "insufficient_credits_error",
    "code": "insufficient_credits",
    "message": "Your account balance ($0.50) is insufficient for this request (estimated cost: $1.20).",
    "balance_cents": 50,
    "estimated_cost_cents": 120
  }
}

Solution: Add credits to your account via the billing page.

rate_limit_error

You've exceeded your rate limit for the current time window.

Example:

{
  "error": {
    "type": "rate_limit_error",
    "code": "rate_limit_exceeded",
    "message": "Rate limit exceeded. Please retry after 30 seconds.",
    "retry_after": 30
  }
}

Solution: Wait for the time specified in the Retry-After header or retry_after field, then retry.

provider_error

The underlying AI provider (Google, OpenAI, etc.) failed to process the request.

Example:

{
  "error": {
    "type": "provider_error",
    "code": "upstream_error",
    "message": "The model provider returned an error: Content policy violation.",
    "provider": "openai"
  }
}

Solution: Try a different model or check if your content violates the provider's usage policies.

api_error

An unexpected internal error occurred.

Example:

{
  "error": {
    "type": "api_error",
    "code": "internal_error",
    "message": "An unexpected error occurred. Please try again.",
    "request_id": "req_abc123"
  }
}

Solution: Retry the request. If the error persists, contact support with the request_id.

Common Error Codes

CodeHTTP StatusDescriptionSolution
invalid_api_key401API key is invalid or revokedCheck your API key in the dashboard
missing_api_key401No Authorization header providedAdd Authorization: Bearer YOUR_KEY header
insufficient_credits402Account balance too lowAdd credits to your account
missing_image400No image in requestInclude an image_url or file in messages
invalid_image_url400Image URL not accessibleUse a publicly accessible URL or base64
unsupported_format400File format not supportedUse PNG, JPG, WEBP, GIF, or PDF
image_too_large413Image exceeds 20MB limitCompress or resize the image
model_not_found404Model ID doesn't existCheck /v1/models for valid IDs
context_length_exceeded400Document too large for modelUse a model with larger context or split document
rate_limit_exceeded429Too many requestsWait and retry with exponential backoff
upstream_error502Provider API failedRetry or try a different model
timeout504Request took too longRetry with a smaller document

Handling Errors in Code

Python

import openai
from openai import OpenAI

client = OpenAI(
    base_url="https://api.docsrouter.com/v1",
    api_key="YOUR_API_KEY"
)

try:
    response = client.chat.completions.create(
        model="google/gemini-2.0-flash-001",
        messages=[...]
    )
except openai.AuthenticationError as e:
    print(f"Authentication failed: {e}")
except openai.RateLimitError as e:
    print(f"Rate limited. Retry after: {e.response.headers.get('Retry-After')}")
except openai.BadRequestError as e:
    print(f"Invalid request: {e}")
except openai.APIError as e:
    print(f"API error: {e}")

JavaScript/TypeScript

import OpenAI from 'openai';

const client = new OpenAI({
  baseURL: 'https://api.docsrouter.com/v1',
  apiKey: 'YOUR_API_KEY',
});

try {
  const response = await client.chat.completions.create({
    model: 'google/gemini-2.0-flash-001',
    messages: [...]
  });
} catch (error) {
  if (error instanceof OpenAI.AuthenticationError) {
    console.error('Invalid API key');
  } else if (error instanceof OpenAI.RateLimitError) {
    console.error('Rate limited, retry later');
  } else if (error instanceof OpenAI.BadRequestError) {
    console.error('Invalid request:', error.message);
  } else {
    console.error('Unexpected error:', error);
  }
}

Retry Strategy

For transient errors (429, 500, 502, 503, 504), implement exponential backoff:

import time
import random

def make_request_with_retry(func, max_retries=5):
    for attempt in range(max_retries):
        try:
            return func()
        except openai.RateLimitError as e:
            if attempt == max_retries - 1:
                raise
            wait_time = (2 ** attempt) + random.uniform(0, 1)
            time.sleep(wait_time)
        except openai.APIError as e:
            if e.status_code in [500, 502, 503, 504]:
                if attempt == max_retries - 1:
                    raise
                wait_time = (2 ** attempt) + random.uniform(0, 1)
                time.sleep(wait_time)
            else:
                raise

Getting Help

If you encounter persistent errors:

  1. Check the status page for any ongoing incidents
  2. Review the error message and request_id
  3. Search the documentation for the specific error code
  4. Contact support at [email protected] with your request_id

On this page