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

# Error Handling

> Handle errors gracefully in your application

# Error Handling

The PolarGrid SDKs provide typed errors for robust error handling.

## Error Types

| Error | Status | Description |
| - | - | - |
| `AuthenticationError` | 401 | Invalid or expired API key |
| `ValidationError` | 400 | Invalid request parameters |
| `NotFoundError` | 404 | Resource not found |
| `RateLimitError` | 429 | [Rate limit](https://polargrid.mintlify.site/guides/rate-limits.md) exceeded |
| `ServerError` | 5xx | Server-side error |
| `NetworkError` | — | Connection failed |
| `TimeoutError` | — | Request timed out |

## Basic Error Handling

```javascript JavaScript theme={null}
import {
  PolarGrid,
  isPolarGridError,
  AuthenticationError,
  ValidationError,
  RateLimitError,
  NetworkError,
  TimeoutError,
} from '@polargrid/polargrid-sdk';

try {
  const response = await client.chatCompletion({
    model: 'qwen-3.8-27b',
    messages: [{ role: 'user', content: 'Hello' }],
  });
} catch (error) {
  if (isPolarGridError(error)) {
    console.error(`Error: ${error.message}`);
    console.error(`Request ID: ${error.requestId}`);
    
    if (error instanceof AuthenticationError) {
      // Redirect to login or refresh API key
      console.error('Please check your API key');
    } else if (error instanceof ValidationError) {
      // Fix request parameters
      console.error('Invalid parameters:', error.details);
    } else if (error instanceof RateLimitError) {
      // Wait and retry
      console.error(`Retry after ${error.retryAfter} seconds`);
    } else if (error instanceof NetworkError) {
      // Check connection
      console.error('Network error - check your connection');
    } else if (error instanceof TimeoutError) {
      // Increase timeout or retry
      console.error('Request timed out');
    }
  } else {
    // Unknown error
    throw error;
  }
}
```

```python Python theme={null}
from polargrid import (
    PolarGrid,
    PolarGridError,
    AuthenticationError,
    ValidationError,
    RateLimitError,
    NetworkError,
    TimeoutError,
)

try:
    response = await client.chat_completion({
        "model": "qwen-3.8-27b",
        "messages": [{"role": "user", "content": "Hello"}],
    })
except PolarGridError as e:
    print(f"Error: {e.message}")
    print(f"Request ID: {e.request_id}")
    
    if isinstance(e, AuthenticationError):
        print("Please check your API key")
    elif isinstance(e, ValidationError):
        print(f"Invalid parameters: {e.details}")
    elif isinstance(e, RateLimitError):
        print(f"Retry after {e.retry_after} seconds")
    elif isinstance(e, NetworkError):
        print("Network error - check your connection")
    elif isinstance(e, TimeoutError):
        print("Request timed out")
```

## Retry Logic

The SDKs include automatic retry with exponential backoff for transient errors. Configure with:

```javascript theme={null}
const client = new PolarGrid({
  apiKey: 'pg_...',
  maxRetries: 3,  // Default: 3
  timeout: 30000, // Default: 30s
});
```

### Custom Retry

For more control:

```javascript theme={null}
async function withRetry(fn, maxRetries = 3) {
  let lastError;
  
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      return await fn();
    } catch (error) {
      lastError = error;
      
      // Don't retry auth errors
      if (error instanceof AuthenticationError) {
        throw error;
      }
      
      // Don't retry validation errors
      if (error instanceof ValidationError) {
        throw error;
      }
      
      // Exponential backoff
      const delay = Math.pow(2, attempt) * 1000;
      await new Promise(r => setTimeout(r, delay));
    }
  }
  
  throw lastError;
}

// Usage
const response = await withRetry(() => 
  client.chatCompletion({
    model: 'qwen-3.8-27b',
    messages: [{ role: 'user', content: 'Hello' }],
  })
);
```

## Rate Limiting

When rate limited, the `RateLimitError` includes a `retryAfter` property (populated when the server sends a `Retry-After` header; otherwise `undefined`, so fall back to a fixed delay as shown below). PolarGrid allows 100 requests per minute per user, counted independently on each edge node. See the [Rate Limits guide](https://polargrid.mintlify.site/guides/rate-limits.md) for full details, retry strategies, and production best practices.

```javascript theme={null}
try {
  const response = await client.chatCompletion(request);
} catch (error) {
  if (error instanceof RateLimitError) {
    const waitMs = (error.retryAfter || 60) * 1000;
    await new Promise(r => setTimeout(r, waitMs));
    // Retry request
  }
}
```

## Request IDs

Every request includes a unique ID for debugging. Include it when contacting support:

```javascript theme={null}
try {
  const response = await client.chatCompletion(request);
} catch (error) {
  if (isPolarGridError(error)) {
    console.error(`Request ID for support: ${error.requestId}`);
  }
}
```

## Validation Errors

Validation errors include details about what's wrong:

```javascript theme={null}
try {
  await client.chatCompletion({
    model: 'qwen-3.8-27b',
    messages: [],  // Empty messages array
  });
} catch (error) {
  if (error instanceof ValidationError) {
    // error.message: "Messages array is required and cannot be empty"
    // error.details: { field: 'messages', reason: 'empty' }
  }
}
```

## Debug Mode

Enable debug logging to see request/response details:

```javascript theme={null}
const client = new PolarGrid({
  apiKey: 'pg_...',
  debug: true,
});

// Logs:
// [PolarGrid] Making request (attempt 1): url=..., method=POST
// [PolarGrid] Request successful: requestId=..., status=200
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.