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

# Error Codes

> HTTP status codes and error responses from the Audixa API

The Audixa API uses standard HTTP status codes to indicate the success or failure of requests. This guide documents all possible error responses.

## Error Response Format

All error responses follow a consistent JSON format:

```json theme={null}
{
  "detail": "Human-readable error message"
}
```

Some errors may include additional context:

```json theme={null}
{
  "detail": "Validation error",
  "errors": [
    {"field": "text", "message": "Text is required"},
    {"field": "voice_id", "message": "Invalid voice ID"}
  ]
}
```

## HTTP Status Codes

### Success Codes

| Code  | Status  | Description                               |
| ----- | ------- | ----------------------------------------- |
| `200` | OK      | Request succeeded (GET requests)          |
| `201` | Created | Resource created successfully (POST /tts) |

### Client Error Codes

| Code  | Status               | Description                                       |
| ----- | -------------------- | ------------------------------------------------- |
| `400` | Bad Request          | Invalid request parameters                        |
| `401` | Unauthorized         | Missing or invalid API key                        |
| `402` | Payment Required     | Insufficient balance                              |
| `404` | Not Found            | Resource not found (e.g., invalid generation\_id) |
| `422` | Unprocessable Entity | Validation error                                  |
| `429` | Too Many Requests    | Rate limit exceeded                               |

### Server Error Codes

| Code  | Status                | Description                     |
| ----- | --------------------- | ------------------------------- |
| `500` | Internal Server Error | Unexpected server error         |
| `503` | Service Unavailable   | Service temporarily unavailable |

### WebSocket Close Codes

| Code   | Description                                                                            |
| ------ | -------------------------------------------------------------------------------------- |
| `1003` | **Invalid Payload**: The server received data it cannot accept (e.g., malformed JSON). |
| `1008` | **Policy Violation**: Authentication failed (e.g., invalid API key).                   |
| `1011` | **Internal Error**: Unexpected server condition (e.g., Redis failure).                 |

## Common Errors

### 400 Bad Request

Returned when request parameters are missing or invalid.

<ResponseExample>
  ```json 400 Bad Request theme={null}
  {
    "detail": "Validation error",
    "errors": [
      {"field": "text", "message": "Text is required"},
      {"field": "model", "message": "Model must be 'base' or 'advanced'"}
    ]
  }
  ```
</ResponseExample>

**Common causes:**

* Missing required fields (`text`, `voice_id`, `model`)
* Invalid `model` value (must be `base` or `advanced`)
* Text exceeds maximum length

***

### 401 Unauthorized

Returned when authentication fails.

<ResponseExample>
  ```json 401 Unauthorized theme={null}
  {
    "detail": "Invalid or missing API key"
  }
  ```
</ResponseExample>

**Common causes:**

* Missing `x-api-key` header
* Invalid or revoked API key

***

### 402 Payment Required

Returned when your account has insufficient balance.

<ResponseExample>
  ```json 402 Payment Required theme={null}
  {
    "detail": "Insufficient Balance"
  }
  ```
</ResponseExample>

**Solution:** Add funds via the [Billing Dashboard](https://audixa.ai/dashboard/billing).

***

### 404 Not Found

Returned when a requested resource doesn't exist.

<ResponseExample>
  ```json 404 Not Found theme={null}
  {
    "detail": "Generation not found"
  }
  ```
</ResponseExample>

**Common causes:**

* Invalid `generation_id` when checking status
* Generation expired (older than 24 hours)

***

### 429 Too Many Requests

Returned when you exceed the rate limit.

<ResponseExample>
  ```json 429 Too Many Requests theme={null}
  {
    "detail": "Rate limit exceeded. Please retry after 30 seconds."
  }
  ```
</ResponseExample>

**Solution:** Implement exponential backoff retry logic. See [Rate Limits](/guides/rate-limits).

***

### 500 Internal Server Error

Returned when an unexpected server error occurs.

<ResponseExample>
  ```json 500 Internal Server Error theme={null}
  {
    "detail": "An unexpected error occurred. Please try again."
  }
  ```
</ResponseExample>

**Solution:** Retry the request. If the error persists, contact [support@audixa.ai](mailto:support@audixa.ai).

## Error Handling Example

Both SDKs provide typed error classes for robust error handling:

<CodeGroup>
  ```python Python theme={null}
  import audixa
  from audixa.exceptions import (
      AudixaError,
      AuthenticationError,
      RateLimitError,
      InsufficientBalanceError,
  )

  audixa.set_api_key("YOUR_API_KEY")

  try:
      audio_url = audixa.tts_and_wait(
          "Hello from Audixa!",
          voice_id="am_ethan",
          model="base",
      )
      print("Success:", audio_url)
  except AuthenticationError:
      print("Authentication failed. Check your API key.")
  except InsufficientBalanceError:
      print("Insufficient balance. Please add funds.")
  except RateLimitError as e:
      print(f"Rate limited. Retry after {e.retry_after} seconds.")
  except AudixaError as e:
      print(f"API Error ({e.status_code}): {e.message}")
  ```

  ```typescript TypeScript theme={null}
  import Audixa, { AudixaError } from 'audixa';

  const audixa = new Audixa('YOUR_API_KEY');

  try {
    const audioUrl = await audixa.generateTTS({
      text: 'Hello from Audixa!',
      voice_id: 'am_ethan',
      model: 'base'
    });
    console.log('Success:', audioUrl);
  } catch (error) {
    if (error instanceof AudixaError) {
      switch (error.code) {
        case 'AUTHENTICATION_ERROR':
          console.log('Authentication failed. Check your API key.');
          break;
        case 'INSUFFICIENT_BALANCE':
          console.log('Insufficient balance. Please add funds.');
          break;
        case 'RATE_LIMITED':
          console.log('Rate limited. Retry later.');
          break;
        default:
          console.log(`Error (${error.statusCode}): ${error.message}`);
      }
    }
  }
  ```

  ```javascript JavaScript theme={null}
  import Audixa, { AudixaError } from 'audixa';

  const audixa = new Audixa('YOUR_API_KEY');

  try {
    const audioUrl = await audixa.generateTTS({
      text: 'Hello from Audixa!',
      voice_id: 'am_ethan',
      model: 'base'
    });
    console.log('Success:', audioUrl);
  } catch (error) {
    if (error instanceof AudixaError) {
      switch (error.code) {
        case 'AUTHENTICATION_ERROR':
          console.log('Authentication failed. Check your API key.');
          break;
        case 'INSUFFICIENT_BALANCE':
          console.log('Insufficient balance. Please add funds.');
          break;
        case 'RATE_LIMITED':
          console.log('Rate limited. Retry later.');
          break;
        default:
          console.log(`Error (${error.statusCode}): ${error.message}`);
      }
    }
  }
  ```
</CodeGroup>
