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
| Field | Type | Description |
|---|---|---|
type | string | The category of error (see Error Types below) |
code | string | A specific error code for programmatic handling |
message | string | A human-readable description of the error |
param | string | The parameter that caused the error (if applicable) |
request_id | string | Unique identifier for the request (useful for support) |
HTTP Status Codes
| Code | Name | Description | Retry? |
|---|---|---|---|
200 | OK | Request successful | N/A |
400 | Bad Request | Invalid parameters or malformed request | No |
401 | Unauthorized | Missing or invalid API key | No |
402 | Payment Required | Insufficient credits in account | No* |
403 | Forbidden | API key lacks required permissions | No |
404 | Not Found | Endpoint or model does not exist | No |
413 | Payload Too Large | Request body exceeds size limit | No |
422 | Unprocessable Entity | Valid JSON but semantic errors | No |
429 | Too Many Requests | Rate limit exceeded | Yes |
500 | Internal Server Error | Unexpected server error | Yes |
502 | Bad Gateway | Upstream provider unavailable | Yes |
503 | Service Unavailable | DocsRouter temporarily unavailable | Yes |
504 | Gateway Timeout | Request timed out | Yes |
* Retry after adding credits to your account
Error Types
authentication_error
Issues with your API key or account authentication.
Common causes:
- Missing
Authorizationheader - 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
| Code | HTTP Status | Description | Solution |
|---|---|---|---|
invalid_api_key | 401 | API key is invalid or revoked | Check your API key in the dashboard |
missing_api_key | 401 | No Authorization header provided | Add Authorization: Bearer YOUR_KEY header |
insufficient_credits | 402 | Account balance too low | Add credits to your account |
missing_image | 400 | No image in request | Include an image_url or file in messages |
invalid_image_url | 400 | Image URL not accessible | Use a publicly accessible URL or base64 |
unsupported_format | 400 | File format not supported | Use PNG, JPG, WEBP, GIF, or PDF |
image_too_large | 413 | Image exceeds 20MB limit | Compress or resize the image |
model_not_found | 404 | Model ID doesn't exist | Check /v1/models for valid IDs |
context_length_exceeded | 400 | Document too large for model | Use a model with larger context or split document |
rate_limit_exceeded | 429 | Too many requests | Wait and retry with exponential backoff |
upstream_error | 502 | Provider API failed | Retry or try a different model |
timeout | 504 | Request took too long | Retry 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:
raiseGetting Help
If you encounter persistent errors:
- Check the status page for any ongoing incidents
- Review the error message and
request_id - Search the documentation for the specific error code
- Contact support at [email protected] with your
request_id