Error Reference
Comprehensive guide to handling errors returned by the moder8r API.
Error Response Format
All API errors follow a consistent JSON format with an error object containing detailed information:
Error Response Structure
{
"error": {
"code": "invalid_api_key",
"message": "The provided API key is invalid or has been revoked",
"type": "authentication_error"
},
"request_id": "req_1a2b3c4d5e6f"
}code
Machine-readable error identifier for programmatic handling
message
Human-readable description of what went wrong
type
Category of error for general error handling logic
Error Codes Reference
| Error Code | Status | Category | Description | Solution |
|---|---|---|---|---|
missing_api_key | 401 | Authentication | No Authorization header provided | Add Bearer token to Authorization header |
invalid_api_key | 401 | Authentication | Invalid or revoked API key | Check your API key in the dashboard |
invalid_json | 400 | Request | Malformed JSON in request body | Ensure request body is valid JSON |
missing_content | 400 | Request | Required 'content' field missing from request | Include 'content' field in request body |
content_too_long | 400 | Request | Content exceeds maximum length limit | Reduce content size to under 10,000 characters |
quota_exceeded | 402 | Rate Limiting | Monthly request limit reached | Upgrade your plan or wait for next billing cycle |
rate_limit_exceeded | 429 | Rate Limiting | Per-minute rate limit exceeded | Implement exponential backoff and retry logic |
internal_server_error | 500 | Server | Unexpected server error occurred | Retry request after a short delay. Contact support if persists. |
service_unavailable | 503 | Server | Service temporarily unavailable | Retry request with exponential backoff |
HTTP Status Codes
| Status Code | Meaning | Action |
|---|---|---|
200 | Success | Process the response data |
400 | Bad Request | Fix request format/content and retry |
401 | Unauthorized | Check API key and authentication |
402 | Payment Required | Upgrade plan or wait for reset |
429 | Too Many Requests | Implement backoff and retry |
500 | Server Error | Retry with exponential backoff |
Retry Logic Examples
⚠️ Rate Limiting Best Practices
Always implement exponential backoff for rate-limited requests (429 status). Respect the Retry-After header when provided.
JavaScript Implementation
// JavaScript - Exponential backoff retry logic
async function moderateWithRetry(content, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetch('https://api.moder8r.app/v1/moderate/text', {
method: 'POST',
headers: {
'Authorization': 'Bearer m8r_sk_your_key_here',
'Content-Type': 'application/json',
},
body: JSON.stringify({ content })
});
if (response.ok) {
return await response.json();
}
// Handle rate limiting with exponential backoff
if (response.status === 429) {
const retryAfter = response.headers.get('Retry-After');
const delay = retryAfter ? parseInt(retryAfter) * 1000 : Math.pow(2, attempt) * 1000;
console.log(`Rate limited. Retrying after ${delay}ms (attempt ${attempt})`);
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
// Handle other errors
const error = await response.json();
throw new Error(`API Error: ${error.error.message}`);
} catch (err) {
if (attempt === maxRetries) {
throw err;
}
// Exponential backoff for network errors
const delay = Math.pow(2, attempt) * 1000;
console.log(`Request failed. Retrying after ${delay}ms (attempt ${attempt})`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}Python Implementation
# Python - Retry logic with backoff
import time
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
def create_session_with_retries():
"""Create a requests session with retry strategy"""
session = requests.Session()
retry_strategy = Retry(
total=3,
backoff_factor=1,
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["POST", "GET"]
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session
def moderate_text_with_retry(content):
"""Moderate text with automatic retries"""
session = create_session_with_retries()
url = 'https://api.moder8r.app/v1/moderate/text'
headers = {
'Authorization': 'Bearer m8r_sk_your_key_here',
'Content-Type': 'application/json'
}
data = {'content': content}
try:
response = session.post(url, headers=headers, json=data, timeout=30)
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 429:
retry_after = e.response.headers.get('Retry-After', 60)
print(f"Rate limited. Wait {retry_after} seconds before retrying.")
raise
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
raiseError Handling Guidelines
✅ Best Practices
- • Always check HTTP status codes first
- • Parse error response for specific error codes
- • Implement exponential backoff for retries
- • Log errors with request_id for debugging
- • Handle rate limits gracefully
- • Validate input before making requests
- • Set reasonable timeouts
❌ Common Mistakes
- • Ignoring HTTP status codes
- • Not implementing retry logic
- • Aggressive retry without backoff
- • Not handling quota exceeded errors
- • Missing request validation
- • Exposing error details to end users
- • Not monitoring error rates