Errors
API error codes and handling
When an API request fails, you'll receive an error response with a status code and message.
Error Response Format
{
"error": {
"code": "invalid_api_key",
"message": "The API key provided is invalid."
}
}HTTP Status Codes
| Status | Description |
|---|---|
400 | Bad Request — Invalid parameters |
401 | Unauthorized — Invalid or missing API key |
402 | Payment Required — Insufficient credits |
403 | Forbidden — Access denied |
404 | Not Found — Resource doesn't exist |
429 | Too Many Requests — Rate limit exceeded |
500 | Internal Server Error — Server error |
503 | Service Unavailable — Temporary outage |
Common Error Codes
| Code | Description |
|---|---|
invalid_api_key | The API key is invalid or revoked |
insufficient_credits | Not enough credits to complete the request |
rate_limit_exceeded | Too many requests in a short period |
invalid_model | The specified model doesn't exist |
invalid_request | The request body is malformed |
context_length_exceeded | Message array exceeds model's context limit |
Handling Errors
Retry with Backoff
For 429 and 5xx errors, implement exponential backoff before retrying.
async function fetchWithRetry(url: string, options: RequestInit, retries = 3) {
for (let i = 0; i < retries; i++) {
const response = await fetch(url, options);
if (response.ok) return response;
if (response.status === 429 || response.status >= 500) {
await new Promise((r) => setTimeout(r, Math.pow(2, i) * 1000));
continue;
}
throw new Error(`API Error: ${response.status}`);
}
throw new Error("Max retries exceeded");
}