> ## Documentation Index
> Fetch the complete documentation index at: https://docs.voidai.app/llms.txt
> Use this file to discover all available pages before exploring further.

# Error Handling

> Understanding and handling VoidAI API errors

VoidAI returns errors in a consistent JSON format. Understanding these errors helps you build robust applications.

## Error Response Format

All errors follow this structure:

```json theme={null}
{
  "error": {
    "message": "Human-readable error description",
    "type": "api_error",
    "code": "ERROR_CODE",
    "reference_id": "req_1701691200_abc123",
    "timestamp": "2024-12-04T12:00:00.000Z"
  }
}
```

| Field          | Description                                            |
| -------------- | ------------------------------------------------------ |
| `message`      | Human-readable description of the error                |
| `type`         | Error category (e.g., `api_error`, `validation_error`) |
| `code`         | Machine-readable error code                            |
| `reference_id` | Unique ID for support inquiries                        |
| `timestamp`    | When the error occurred                                |

## HTTP Status Codes

| Status | Description                                                   |
| ------ | ------------------------------------------------------------- |
| `400`  | Bad Request - Invalid parameters or malformed request         |
| `401`  | Unauthorized - Invalid or missing API key                     |
| `403`  | Forbidden - Access denied (IP restrictions, disabled account) |
| `404`  | Not Found - Resource doesn't exist                            |
| `429`  | Too Many Requests - Rate limit exceeded                       |
| `500`  | Internal Server Error - Something went wrong on our end       |
| `503`  | Service Unavailable - Temporary outage                        |

## Common Error Codes

### Authentication Errors

| Code                  | Description                              |
| --------------------- | ---------------------------------------- |
| `MISSING_HEADER`      | No Authorization header provided         |
| `INVALID_FORMAT`      | Authorization header format is incorrect |
| `INVALID_KEY`         | API key is invalid or doesn't exist      |
| `INVALID_OAUTH_TOKEN` | OAuth token is invalid                   |
| `ACCOUNT_DISABLED`    | User account has been disabled           |
| `IP_ACCESS_DENIED`    | Request IP not in allowlist              |

### Request Errors

| Code                   | Description                         |
| ---------------------- | ----------------------------------- |
| `INVALID_MODEL`        | Requested model doesn't exist       |
| `INSUFFICIENT_CREDITS` | Not enough credits for this request |
| `RATE_LIMIT_EXCEEDED`  | Too many requests                   |
| `VALIDATION_ERROR`     | Request body validation failed      |

### Provider Errors

| Code                   | Description                         |
| ---------------------- | ----------------------------------- |
| `PROVIDER_ERROR`       | Upstream provider returned an error |
| `PROVIDER_UNAVAILABLE` | Provider is temporarily unavailable |
| `MODEL_UNAVAILABLE`    | Specific model is unavailable       |

## Handling Errors

### Python

```python theme={null}
from openai import OpenAI, APIError, AuthenticationError, RateLimitError

client = OpenAI(
    api_key="sk-voidai-your_key_here",
    base_url="https://api.voidai.app/v1"
)

try:
    response = client.chat.completions.create(
        model="gpt-5.1",
        messages=[{"role": "user", "content": "Hello!"}]
    )
except AuthenticationError as e:
    print(f"Authentication failed: {e.message}")
    # Check your API key
except RateLimitError as e:
    print(f"Rate limit hit: {e.message}")
    # Implement exponential backoff
except APIError as e:
    print(f"API error: {e.message}")
    print(f"Reference ID: {e.body.get('error', {}).get('reference_id')}")
    # Log the reference_id for support
```

### TypeScript

```typescript theme={null}
import OpenAI, { APIError, AuthenticationError, RateLimitError } from 'openai';

const client = new OpenAI({
  apiKey: 'sk-voidai-your_key_here',
  baseURL: 'https://api.voidai.app/v1'
});

try {
  const response = await client.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: 'Hello!' }]
  });
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.log(`Authentication failed: ${error.message}`);
    // Check your API key
  } else if (error instanceof RateLimitError) {
    console.log(`Rate limit hit: ${error.message}`);
    // Implement exponential backoff
  } else if (error instanceof APIError) {
    console.log(`API error: ${error.message}`);
    // Log for debugging
  }
}
```

## Retry Strategy

For transient errors (5xx, rate limits), implement exponential backoff:

```python theme={null}
import time
from openai import OpenAI, RateLimitError, APIError

def make_request_with_retry(client, max_retries=3):
    for attempt in range(max_retries):
        try:
            return client.chat.completions.create(
                model="gpt-4",
                messages=[{"role": "user", "content": "Hello!"}]
            )
        except RateLimitError:
            if attempt < max_retries - 1:
                wait_time = (2 ** attempt) + 1  # 1, 3, 5 seconds
                print(f"Rate limited. Waiting {wait_time}s...")
                time.sleep(wait_time)
            else:
                raise
        except APIError as e:
            if e.status_code >= 500 and attempt < max_retries - 1:
                wait_time = (2 ** attempt) + 1
                print(f"Server error. Waiting {wait_time}s...")
                time.sleep(wait_time)
            else:
                raise
```

## Debugging Tips

<AccordionGroup>
  <Accordion title="Save the reference_id">
    Every error includes a `reference_id`. Save this for support inquiries - it helps us track down issues quickly.
  </Accordion>

  <Accordion title="Check your API key">
    Most authentication errors are caused by typos or using the wrong API key. Double-check your key starts with `sk-voidai-`.
  </Accordion>

  <Accordion title="Verify the model exists">
    Use the [Models endpoint](/api-reference/models/list) to see available models before making requests.
  </Accordion>

  <Accordion title="Check your credit balance">
    Insufficient credits will cause requests to fail. Check your dashboard for your current balance.
  </Accordion>
</AccordionGroup>

## Getting Help

If you encounter persistent errors:

1. Note the `reference_id` from the error response
2. Check your [dashboard](https://voidai.app) for account status
3. Join our [Discord](https://discord.gg/voidai) for community support
