# Error Handling

## Overview

Tokenlio API uses standard HTTP status codes and returns detailed error responses to help you diagnose and handle issues.

## HTTP Status Codes

| Code | Meaning | Description |
|------|---------|-------------|
| 200 | OK | Request succeeded |
| 400 | Bad Request | Invalid request parameters |
| 401 | Unauthorized | Invalid or missing API key |
| 403 | Forbidden | Insufficient permissions |
| 404 | Not Found | Resource not found |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Server error |
| 502 | Bad Gateway | Upstream provider error |
| 503 | Service Unavailable | Temporary unavailability |

## Error Response Format

All errors return JSON with the following structure:

```json
{
  "error": {
    "code": "invalid_api_key",
    "message": "Invalid authentication credentials",
    "type": "authentication_error",
    "param": null
  }
}
```

### Fields

- `code`: Machine-readable error code
- `message`: Human-readable error message
- `type`: Error category
- `param`: Parameter that caused the error (if applicable)

## Error Types

### Authentication Errors (401)

**Invalid API Key**
```json
{
  "error": {
    "code": "invalid_api_key",
    "message": "Invalid API key provided",
    "type": "authentication_error"
  }
}
```

**Solution**: Check your API key is correct and starts with `tk-`

---

**Missing API Key**
```json
{
  "error": {
    "code": "missing_api_key",
    "message": "No API key provided",
    "type": "authentication_error"
  }
}
```

**Solution**: Include `Authorization: Bearer tk-...` header

### Validation Errors (400)

**Invalid Request**
```json
{
  "error": {
    "code": "invalid_request",
    "message": "Missing required parameter: messages",
    "type": "invalid_request_error",
    "param": "messages"
  }
}
```

**Solution**: Check API documentation for required parameters

---

**Invalid Model**
```json
{
  "error": {
    "code": "model_not_found",
    "message": "The model 'gpt-5' does not exist",
    "type": "invalid_request_error",
    "param": "model"
  }
}
```

**Solution**: Use `GET /v1/models` to list available models

### Rate Limit Errors (429)

```json
{
  "error": {
    "code": "rate_limit_exceeded",
    "message": "Rate limit exceeded. Please retry after 60 seconds",
    "type": "rate_limit_error"
  }
}
```

**Solution**: Implement exponential backoff and respect `Retry-After` header

### Insufficient Balance (402)

```json
{
  "error": {
    "code": "insufficient_balance",
    "message": "Insufficient account balance. Please top up",
    "type": "payment_error"
  }
}
```

**Solution**: Add funds at [api.tokenlio.ai/billing](https://api.tokenlio.ai/billing)

### Server Errors (500, 502, 503)

```json
{
  "error": {
    "code": "internal_error",
    "message": "An internal error occurred. Please try again",
    "type": "server_error"
  }
}
```

**Solution**: Retry with exponential backoff. Contact support if persistent.

## Best Practices

### Retry Logic

Implement exponential backoff for retryable errors:

```python
import time
from openai import OpenAI, APIError, RateLimitError

client = OpenAI(
    api_key="your-tokenlio-key",
    base_url="https://api.tokenlio.ai/v1"
)

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

### Error Logging

Log errors for debugging:

```python
import logging

logger = logging.getLogger(__name__)

try:
    response = client.chat.completions.create(...)
except Exception as e:
    logger.error(f"API request failed: {e}", exc_info=True)
    # Handle error appropriately
```

### User-Friendly Messages

Don't expose raw error messages to end users:

```python
try:
    response = make_api_call()
except RateLimitError:
    return "Service is busy. Please try again in a moment."
except InsufficientBalanceError:
    return "Account credit depleted. Please contact support."
except APIError:
    return "Unable to process request. Please try again later."
```

## Response Headers

Useful headers in error responses:

```
X-Request-ID: req_abc123xyz
Retry-After: 60
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1704067200
```

- `X-Request-ID`: Include when contacting support
- `Retry-After`: Seconds to wait before retry
- `X-RateLimit-Remaining`: Requests remaining in current window
- `X-RateLimit-Reset`: Unix timestamp when limit resets

## Common Issues

### SSL Certificate Errors

**Error**: `SSL: CERTIFICATE_VERIFY_FAILED`

**Solution**:
```python
# Ensure you're using https://
client = OpenAI(
    api_key="tk-...",
    base_url="https://api.tokenlio.ai/v1"  # https, not http
)
```

### Timeout Errors

**Error**: `Request timeout after 60s`

**Solution**: Increase timeout for long-running requests:
```python
import httpx

client = OpenAI(
    api_key="tk-...",
    base_url="https://api.tokenlio.ai/v1",
    http_client=httpx.Client(timeout=120.0)  # 120 seconds
)
```

### Connection Errors

**Error**: `Connection refused` or `Name resolution failed`

**Solution**:
- Check internet connectivity
- Verify firewall/proxy settings
- Check DNS resolution: `nslookup api.tokenlio.ai`

## Getting Help

If errors persist:
1. Check [Status Page](https://status.tokenlio.ai) for outages
2. Review [FAQ](/support/faq)
3. Contact support with:
   - `X-Request-ID` from error response
   - Error code and message
   - Timestamp
   - Request details (excluding sensitive data)

**Support Email**: [support@tokenlio.ai](mailto:support@tokenlio.ai)

## Error Code Reference

| Code | HTTP | Retryable | Description |
|------|------|-----------|-------------|
| `invalid_api_key` | 401 | No | API key is invalid |
| `missing_api_key` | 401 | No | No API key provided |
| `invalid_request` | 400 | No | Invalid parameters |
| `model_not_found` | 404 | No | Model doesn't exist |
| `rate_limit_exceeded` | 429 | Yes | Too many requests |
| `insufficient_balance` | 402 | No | Account balance too low |
| `internal_error` | 500 | Yes | Server error |
| `upstream_error` | 502 | Yes | Provider error |
| `service_unavailable` | 503 | Yes | Temporary unavailability |
