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

# Error Reference

> Complete guide to Babou API error codes and how to handle them

## Error Response Format

All error responses from the Babou API follow a consistent JSON structure:

```json theme={null}
{
  "error": "Human-readable error message",
  "code": "ERROR_CODE",
  "hint": "Optional guidance on how to fix the error"
}
```

<ResponseField name="error" type="string">
  A human-readable description of what went wrong
</ResponseField>

<ResponseField name="code" type="string">
  A machine-readable error code for programmatic handling
</ResponseField>

<ResponseField name="hint" type="string">
  Optional additional guidance on resolving the error
</ResponseField>

## HTTP Status Codes

The Babou API uses standard HTTP status codes:

| Status Code | Meaning                                                       |
| ----------- | ------------------------------------------------------------- |
| `200`       | Success - Request completed successfully                      |
| `400`       | Bad Request - Invalid parameters or request format            |
| `401`       | Unauthorized - Invalid or missing API key                     |
| `404`       | Not Found - Resource doesn't exist or you don't have access   |
| `409`       | Conflict - Resource state conflict (e.g., already processing) |
| `413`       | Payload Too Large - File exceeds size limits                  |
| `429`       | Too Many Requests - Rate limit exceeded                       |
| `500`       | Internal Server Error - Something went wrong on our end       |

## Common Error Codes

### Authentication Errors

<AccordionGroup>
  <Accordion title="UNAUTHORIZED" icon="lock">
    **HTTP Status:** `401`

    **Cause:** Invalid or missing API key

    **Example:**

    ```json theme={null}
    {
      "error": "Unauthorized - Invalid API key",
      "code": "UNAUTHORIZED"
    }
    ```

    **Solution:**

    * Verify your API key is correct
    * Ensure you're including the `Authorization` header
    * Check that your API key hasn't expired
    * Get a new API key from the [dashboard](https://babou.ai)
  </Accordion>

  <Accordion title="INVALID_API_KEY_FORMAT" icon="key">
    **HTTP Status:** `401`

    **Cause:** API key doesn't match the expected format (`sk-bab-*`)

    **Example:**

    ```json theme={null}
    {
      "error": "Invalid API key format",
      "code": "INVALID_API_KEY_FORMAT"
    }
    ```

    **Solution:**

    * Ensure your API key starts with `sk-bab-`
    * Check for typos or truncation
    * Don't add extra characters or whitespace
  </Accordion>

  <Accordion title="API_KEY_EXPIRED" icon="clock">
    **HTTP Status:** `401`

    **Cause:** The API key has passed its expiration date

    **Example:**

    ```json theme={null}
    {
      "error": "API key has expired",
      "code": "API_KEY_EXPIRED"
    }
    ```

    **Solution:**

    * Generate a new API key from your dashboard
    * Update your application with the new key
    * Set up key rotation to prevent future expirations
  </Accordion>
</AccordionGroup>

### Validation Errors

<AccordionGroup>
  <Accordion title="VALIDATION_ERROR" icon="triangle-exclamation">
    **HTTP Status:** `400`

    **Cause:** Request parameters don't meet validation requirements

    **Example:**

    ```json theme={null}
    {
      "error": "Validation failed",
      "code": "VALIDATION_ERROR",
      "hint": "Name must be between 1 and 30 characters"
    }
    ```

    **Common Validation Rules:**

    * Project name: 1-30 characters
    * Project description: max 1000 characters
    * Chapter name: 1-30 characters
    * Chapter duration: positive integer
    * Prompt content: 1-5000 characters

    **Solution:**

    * Check the `hint` field for specific guidance
    * Review the API documentation for parameter requirements
    * Validate input on the client side before sending
  </Accordion>
</AccordionGroup>

### Resource Errors

<AccordionGroup>
  <Accordion title="NOT_FOUND" icon="magnifying-glass">
    **HTTP Status:** `404`

    **Cause:** The requested resource doesn't exist or you don't have access

    **Example:**

    ```json theme={null}
    {
      "error": "Project not found",
      "code": "NOT_FOUND"
    }
    ```

    **Solution:**

    * Verify the ID is correct
    * Check that the resource belongs to your account
    * Ensure the resource hasn't been deleted
    * Use List endpoints to find valid IDs
  </Accordion>

  <Accordion title="CONFLICT" icon="circle-exclamation">
    **HTTP Status:** `409`

    **Cause:** Resource state conflict - operation can't proceed due to current state

    **Common Scenarios:**

    * Another prompt is already being processed for a chapter
    * Export is already in progress for a project

    **Example:**

    ```json theme={null}
    {
      "error": "A prompt is already being processed for this chapter",
      "code": "CONFLICT",
      "hint": "Wait for the current prompt to complete or set force: true to override"
    }
    ```

    **Solution:**

    * Wait for the current operation to complete
    * Check operation status before retrying
    * Use `force: true` parameter if applicable (use cautiously)
  </Accordion>
</AccordionGroup>

### File Upload Errors

<AccordionGroup>
  <Accordion title="FILE_TOO_LARGE" icon="file">
    **HTTP Status:** `413`

    **Cause:** Uploaded file exceeds the 100MB size limit

    **Example:**

    ```json theme={null}
    {
      "error": "File size exceeds maximum allowed size of 100MB",
      "code": "FILE_TOO_LARGE"
    }
    ```

    **Solution:**

    * Compress the file before uploading
    * Split large videos into smaller segments
    * Check file size before upload:
      ```typescript theme={null}
      const stats = fs.statSync(filePath);
      if (stats.size > 100 * 1024 * 1024) {
        throw new Error('File too large');
      }
      ```
  </Accordion>

  <Accordion title="UPLOAD_FAILED" icon="cloud-arrow-up">
    **HTTP Status:** `500`

    **Cause:** Failed to upload file to cloud storage

    **Example:**

    ```json theme={null}
    {
      "error": "Failed to upload file to storage",
      "code": "UPLOAD_FAILED"
    }
    ```

    **Solution:**

    * Retry the upload
    * Check your network connection
    * Verify the file isn't corrupted
    * Contact support if the issue persists
  </Accordion>
</AccordionGroup>

### Rate Limiting

<AccordionGroup>
  <Accordion title="RATE_LIMIT_EXCEEDED" icon="gauge-high">
    **HTTP Status:** `429`

    **Cause:** Too many requests in a short time period

    **Example:**

    ```json theme={null}
    {
      "error": "Rate limit exceeded",
      "code": "RATE_LIMIT_EXCEEDED",
      "hint": "Retry after 60 seconds"
    }
    ```

    **Solution:**

    * Implement exponential backoff
    * Space out your requests
    * Cache responses when possible
    * Contact support for higher rate limits

    **Retry Strategy:**

    ```typescript theme={null}
    async function fetchWithRetry(url: string, options: RequestInit, maxRetries = 3) {
      for (let i = 0; i < maxRetries; i++) {
        const response = await fetch(url, options);

        if (response.status !== 429) {
          return response;
        }

        // Exponential backoff
        const delay = Math.pow(2, i) * 1000;
        await new Promise(r => setTimeout(r, delay));
      }

      throw new Error('Max retries exceeded');
    }
    ```
  </Accordion>
</AccordionGroup>

### Server Errors

<AccordionGroup>
  <Accordion title="INTERNAL_ERROR" icon="server">
    **HTTP Status:** `500`

    **Cause:** An unexpected error occurred on the server

    **Example:**

    ```json theme={null}
    {
      "error": "An internal error occurred",
      "code": "INTERNAL_ERROR"
    }
    ```

    **Solution:**

    * Retry the request after a short delay
    * Check the [status page](https://status.babou.ai) for known issues
    * Contact support if the problem persists
    * Include the request ID if available for faster debugging
  </Accordion>
</AccordionGroup>

## Error Handling Best Practices

### 1. Always Check Response Status

<CodeGroup>
  ```typescript TypeScript theme={null}
  async function makeApiCall(url: string, options: RequestInit) {
    const response = await fetch(url, options);

    if (!response.ok) {
      const error = await response.json();
      throw new Error(`API Error (${response.status}): ${error.error} [${error.code}]`);
    }

    return await response.json();
  }
  ```

  ```python Python theme={null}
  def make_api_call(url, **kwargs):
      response = requests.request(url=url, **kwargs)

      if not response.ok:
          error = response.json()
          raise Exception(f'API Error ({response.status_code}): {error["error"]} [{error["code"]}]')

      return response.json()
  ```
</CodeGroup>

### 2. Implement Retry Logic

```typescript theme={null}
async function retryWithBackoff<T>(
  fn: () => Promise<T>,
  maxRetries = 3,
  baseDelay = 1000
): Promise<T> {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      return await fn();
    } catch (error: any) {
      const isLastAttempt = attempt === maxRetries - 1;

      // Don't retry on client errors (4xx except 429)
      if (error.message.includes('(4') && !error.message.includes('(429')) {
        throw error;
      }

      if (isLastAttempt) {
        throw error;
      }

      const delay = baseDelay * Math.pow(2, attempt);
      console.log(`Retry ${attempt + 1}/${maxRetries} after ${delay}ms...`);
      await new Promise(r => setTimeout(r, delay));
    }
  }

  throw new Error('Max retries exceeded');
}
```

### 3. Handle Specific Error Codes

```typescript theme={null}
async function submitPromptSafe(projectId: string, chapterId: string, content: string) {
  try {
    return await submitPrompt(projectId, chapterId, content);
  } catch (error: any) {
    if (error.message.includes('[CONFLICT]')) {
      // Wait and retry for conflicts
      console.log('Waiting for current operation to complete...');
      await new Promise(r => setTimeout(r, 10000));
      return await submitPrompt(projectId, chapterId, content);
    }

    if (error.message.includes('[UNAUTHORIZED]')) {
      // Don't retry auth errors
      throw new Error('Invalid API key - please check your credentials');
    }

    if (error.message.includes('[VALIDATION_ERROR]')) {
      // Don't retry validation errors
      throw new Error(`Invalid input: ${error.message}`);
    }

    // Retry other errors
    return await retryWithBackoff(() => submitPrompt(projectId, chapterId, content));
  }
}
```

### 4. Log Errors for Debugging

```python theme={null}
import logging

logger = logging.getLogger(__name__)

def api_call_with_logging(func):
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            logger.error(f'API call failed: {func.__name__}', exc_info=True)
            logger.error(f'Args: {args}, Kwargs: {kwargs}')
            raise
    return wrapper

@api_call_with_logging
def create_project(name, description=None):
    # ... API call logic
    pass
```

## Need Help?

If you're experiencing errors that aren't covered here:

<CardGroup cols={2}>
  <Card title="Check API Status" icon="signal" href="https://status.babou.ai">
    View system status and known issues
  </Card>

  <Card title="Contact Support" icon="headset" href="mailto:support@babou.ai">
    Get help from our support team
  </Card>
</CardGroup>
