# Error Handling

This guide covers error responses and how to handle them in your application.

## Error Response Format

All error responses follow a consistent JSON format:

```json
{
  "error": "Error message describing the issue",
  "code": "ERROR_CODE",
  "details": {
    "field": "Additional context about the error"
  }
}
```

## HTTP Status Codes

| Status | Description                               |
| ------ | ----------------------------------------- |
| 200    | Success                                   |
| 201    | Created                                   |
| 400    | Bad Request - Invalid parameters          |
| 401    | Unauthorized - Invalid or missing API key |
| 403    | Forbidden - Insufficient permissions      |
| 404    | Not Found - Resource doesn't exist        |
| 429    | Too Many Requests - Rate limit exceeded   |
| 500    | Internal Server Error                     |
| 502    | Bad Gateway                               |
| 503    | Service Unavailable                       |

## Error Codes

### Authentication Errors (401)

| Code                    | Description                   |
| ----------------------- | ----------------------------- |
| `AUTHENTICATION_FAILED` | API key is invalid or missing |
| `KEY_EXPIRED`           | API key has expired           |
| `KEY_REVOKED`           | API key has been revoked      |

**Example:**

```json
{
  "error": "Invalid API key provided",
  "code": "AUTHENTICATION_FAILED"
}
```

**Resolution:**

- Verify your API key is correct
- Check for typos in the key
- Ensure the key hasn't expired or been revoked
- Contact support if issues persist

### Authorization Errors (403)

| Code                 | Description                             |
| -------------------- | --------------------------------------- |
| `FORBIDDEN`          | Access denied to this resource          |
| `INSUFFICIENT_SCOPE` | API key lacks required permissions      |
| `SANDBOX_ONLY`       | Endpoint only available in sandbox mode |

**Example:**

```json
{
  "error": "Your API key does not have access to this resource",
  "code": "INSUFFICIENT_SCOPE"
}
```

**Resolution:**

- Verify your subscription tier includes this feature
- Check if the endpoint requires a production key
- Contact sales to upgrade your access

### Validation Errors (400)

| Code                | Description                    |
| ------------------- | ------------------------------ |
| `VALIDATION_FAILED` | Request validation failed      |
| `INVALID_PARAMETER` | Parameter has invalid value    |
| `MISSING_PARAMETER` | Required parameter is missing  |
| `INVALID_JSON`      | Request body is not valid JSON |

**Example:**

```json
{
  "error": "Validation failed",
  "code": "VALIDATION_FAILED",
  "details": {
    "q": "Query string is required and must be 1-500 characters",
    "pageSize": "Must be between 1 and 100"
  }
}
```

**Resolution:**

- Check parameter names and types
- Ensure required fields are provided
- Verify values are within allowed ranges
- Review API documentation for correct format

### Resource Errors (404)

| Code                     | Description                     |
| ------------------------ | ------------------------------- |
| `NOT_FOUND`              | Resource does not exist         |
| `ARTICLE_NOT_FOUND`      | Article with given ID not found |
| `ENTITY_NOT_FOUND`       | Entity with given ID not found  |
| `CLAIM_NOT_FOUND`        | Claim with given ID not found   |
| `SUBSCRIPTION_NOT_FOUND` | Alert subscription not found    |

**Example:**

```json
{
  "error": "Article with ID '123' not found",
  "code": "NOT_FOUND"
}
```

**Resolution:**

- Verify the resource ID is correct
- Check if the resource was deleted
- Ensure you have access to the resource

### Rate Limit Errors (429)

| Code                  | Description       |
| --------------------- | ----------------- |
| `RATE_LIMIT_EXCEEDED` | Too many requests |

**Example:**

```json
{
  "error": "Rate limit exceeded. Retry after 60 seconds.",
  "code": "RATE_LIMIT_EXCEEDED",
  "retryAfter": 60
}
```

**Headers:**

```
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 2024-01-15T14:30:00Z
Retry-After: 60
```

**Resolution:**

- Wait for the time specified in `retryAfter`
- Implement exponential backoff
- Consider caching responses
- Upgrade to a higher tier for increased limits

### Server Errors (5xx)

| Code                  | Description                     |
| --------------------- | ------------------------------- |
| `SERVER_ERROR`        | Internal server error           |
| `SERVICE_UNAVAILABLE` | Service temporarily unavailable |
| `TIMEOUT`             | Request processing timed out    |

**Example:**

```json
{
  "error": "An internal error occurred. Please retry.",
  "code": "SERVER_ERROR"
}
```

**Resolution:**

- Retry the request with exponential backoff
- Check https://status.veritas.news for outages
- Contact support if the error persists

## Handling Errors in SDKs

### JavaScript SDK

```javascript
import {
  VeritasClient,
  VeritasError,
  AuthenticationError,
  NotFoundError,
  RateLimitError,
  ValidationError,
  ServerError,
} from '@veritas/b2b-sdk';

const client = new VeritasClient({ apiKey: 'sk_live_...' });

try {
  const article = await client.feed.get('article-id');
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Invalid API key:', error.message);
    // Prompt user to re-authenticate
  } else if (error instanceof NotFoundError) {
    console.error('Article not found:', error.message);
    // Show 404 page or remove from cache
  } else if (error instanceof RateLimitError) {
    console.error(`Rate limited. Retry after ${error.retryAfter}s`);
    // Wait and retry
    await sleep(error.retryAfter * 1000);
    // Retry the request
  } else if (error instanceof ValidationError) {
    console.error('Invalid request:', error.details);
    // Show validation errors to user
  } else if (error instanceof ServerError) {
    console.error('Server error:', error.message);
    // Retry with exponential backoff
  } else if (error instanceof VeritasError) {
    console.error(`API error [${error.code}]: ${error.message}`);
  } else {
    console.error('Unknown error:', error);
  }
}
```

### Python SDK

```python
from veritas_sdk import (
    VeritasClient,
    VeritasError,
    AuthenticationError,
    NotFoundError,
    RateLimitError,
    ValidationError,
    ServerError,
)
import asyncio

client = VeritasClient(api_key="sk_live_...")

try:
    article = await client.feed.get("article-id")
except AuthenticationError as e:
    print(f"Invalid API key: {e.message}")
    # Prompt user to re-authenticate
except NotFoundError as e:
    print(f"Article not found: {e.resource_id}")
    # Show 404 page or remove from cache
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after}s")
    await asyncio.sleep(e.retry_after)
    # Retry the request
except ValidationError as e:
    print(f"Invalid request: {e.details}")
    # Show validation errors to user
except ServerError as e:
    print(f"Server error: {e.message}")
    # Retry with exponential backoff
except VeritasError as e:
    print(f"API error [{e.code}]: {e.message}")
```

## Retry Strategy

For transient errors (5xx, 429, network issues), implement exponential backoff:

```javascript
async function fetchWithRetry(fn, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (error) {
      // Don't retry client errors (4xx) except rate limits
      if (error.status && error.status < 500 && error.status !== 429) {
        throw error;
      }

      if (attempt === maxRetries) {
        throw error;
      }

      // Calculate backoff: 1s, 2s, 4s...
      const delay = Math.min(1000 * Math.pow(2, attempt - 1), 30000);
      // Add jitter
      const jitter = Math.random() * 500;
      await sleep(delay + jitter);
    }
  }
}
```

The official SDKs implement this automatically when `retry: true` is set.

## Best Practices

1. **Always check status codes** - Don't assume requests succeed
2. **Parse error responses** - Extract code and details for better handling
3. **Implement retries** - Use exponential backoff for transient errors
4. **Log request IDs** - Include `X-Request-ID` in error logs for support
5. **Handle rate limits gracefully** - Implement queuing and backoff
6. **Use SDK error classes** - They provide structured error information
7. **Monitor error rates** - Set up alerts for unusual error patterns

## Getting Help

If you encounter persistent errors:

1. Check the [API status page](https://status.veritas.news)
2. Review the [API documentation](./api-reference.md)
3. Search our [developer forum](https://forum.veritas.news)
4. Contact support at api-support@veritas.news with:
   - Request ID from `X-Request-ID` header
   - Full error response
   - Request details (endpoint, parameters)
   - Timestamp of the error
