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

# Error Handling

> Understanding and handling API errors

## Error Response Format

All API errors follow a consistent format:

```json theme={"dark"}
{
  "error": {
    "message": "Human-readable error description",
    "type": "error_category",
    "code": "specific_error_code",
    "param": "field_name_if_applicable"
  }
}
```

| Field     | Description                                                          |
| --------- | -------------------------------------------------------------------- |
| `message` | Human-readable description of what went wrong                        |
| `type`    | Category of error (e.g., `authentication_error`, `validation_error`) |
| `code`    | Specific error code for programmatic handling                        |
| `param`   | The request parameter that caused the error (if applicable)          |

## HTTP Status Codes

| Status | Description                                              |
| ------ | -------------------------------------------------------- |
| `200`  | Success                                                  |
| `201`  | Created (for POST requests that create resources)        |
| `400`  | Bad Request - Invalid parameters or malformed request    |
| `401`  | Unauthorized - Invalid or missing API key                |
| `402`  | Payment Required - Insufficient credits                  |
| `403`  | Forbidden - Access denied to resource                    |
| `404`  | Not Found - Resource doesn't exist                       |
| `429`  | Too Many Requests - Rate limit exceeded                  |
| `500`  | Internal Server Error - Something went wrong on our side |
| `503`  | Service Unavailable - Temporary outage                   |

## Error Types

### Authentication Errors (401)

```json theme={"dark"}
{
  "error": {
    "message": "Invalid API key. Ensure your key starts with 'mvra_live_' and has not been revoked.",
    "type": "authentication_error",
    "code": "invalid_api_key",
    "param": null
  }
}
```

| Code              | Description                         | Solution                                  |
| ----------------- | ----------------------------------- | ----------------------------------------- |
| `missing_api_key` | No Authorization header             | Add `Authorization: Bearer <key>` header  |
| `invalid_api_key` | Key format invalid or doesn't exist | Check key format starts with `mvra_live_` |
| `revoked_api_key` | Key has been revoked                | Create a new API key                      |

### Validation Errors (400)

```json theme={"dark"}
{
  "error": {
    "message": "Invalid value for 'model': must be one of ['mavera-1'].",
    "type": "invalid_request_error",
    "code": "invalid_model",
    "param": "model"
  }
}
```

| Code              | Description                 | Solution                                  |
| ----------------- | --------------------------- | ----------------------------------------- |
| `invalid_model`   | Invalid model specified     | Use `mavera-1`                            |
| `missing_field`   | Required field not provided | Include the required field                |
| `invalid_field`   | Field value is invalid      | Check field requirements in API reference |
| `invalid_persona` | Persona ID doesn't exist    | List personas to get valid IDs            |

### Credit Errors (402)

```json theme={"dark"}
{
  "error": {
    "message": "Insufficient credits. Please upgrade your subscription or wait for your next billing cycle.",
    "type": "insufficient_credits",
    "code": "credits_exhausted",
    "param": null
  }
}
```

| Code                | Description                        | Solution                       |
| ------------------- | ---------------------------------- | ------------------------------ |
| `credits_exhausted` | No credits remaining               | Upgrade plan or wait for reset |
| `budget_exceeded`   | Workspace/project budget limit hit | Increase budget or wait        |

### Rate Limit Errors (429)

```json theme={"dark"}
{
  "error": {
    "message": "Rate limit exceeded. Please retry after 30 seconds.",
    "type": "rate_limit_error",
    "code": "rate_limit_exceeded",
    "param": null
  }
}
```

Check the `Retry-After` header for how long to wait.

### Not Found Errors (404)

```json theme={"dark"}
{
  "error": {
    "message": "Thread not found",
    "type": "not_found_error",
    "code": "resource_not_found",
    "param": "thread_id"
  }
}
```

### Server Errors (500, 503)

```json theme={"dark"}
{
  "error": {
    "message": "An internal error occurred. Please try again later.",
    "type": "api_error",
    "code": "internal_error",
    "param": null
  }
}
```

<Warning>
  If you receive 500 errors consistently, please contact [support@mavera.io](mailto:support@mavera.io)
</Warning>

## Handling Errors in Code

<CodeGroup>
  ```python Python theme={"dark"}
  from openai import OpenAI, APIError, AuthenticationError, RateLimitError

  client = OpenAI(
      api_key="mvra_live_your_key_here",
      base_url="https://app.mavera.io/api/v1",
  )

  try:
      response = client.responses.create(
          model="mavera-1",
          input=[{"role": "user", "content": "Hello"}],
          extra_body={"persona_id": "your_persona_id"},
      )
  except AuthenticationError as e:
      print(f"Authentication failed: {e}")
      # Handle invalid API key
  except RateLimitError as e:
      print(f"Rate limited: {e}")
      # Implement backoff and retry
  except APIError as e:
      if e.status_code == 402:
          print("Insufficient credits")
          # Handle billing issue
      elif e.status_code == 404:
          print("Resource not found")
          # Handle missing resource
      else:
          print(f"API error: {e}")
          # Log and retry for transient errors
  ```

  ```javascript JavaScript theme={"dark"}
  import OpenAI from "openai";

  const client = new OpenAI({
    apiKey: "mvra_live_your_key_here",
    baseURL: "https://app.mavera.io/api/v1",
  });

  try {
    const response = await client.responses.create({
      model: "mavera-1",
      input: [{ role: "user", content: "Hello" }],
      persona_id: "your_persona_id",
    });
  } catch (error) {
    if (error instanceof OpenAI.AuthenticationError) {
      console.error("Authentication failed:", error.message);
    } else if (error instanceof OpenAI.RateLimitError) {
      console.error("Rate limited:", error.message);
      // Implement backoff and retry
    } else if (error instanceof OpenAI.APIError) {
      if (error.status === 402) {
        console.error("Insufficient credits");
      } else if (error.status === 404) {
        console.error("Resource not found");
      } else {
        console.error("API error:", error.message);
      }
    }
  }
  ```

  ```bash cURL theme={"dark"}
  # Check the exit code and response
  response=$(curl -s -w "\n%{http_code}" -X POST \
    https://app.mavera.io/api/v1/responses \
    -H "Authorization: Bearer mvra_live_your_key_here" \
    -H "Content-Type: application/json" \
    -d '{"model": "mavera-1", "input": [{"role": "user", "content": "Hello"}]}')

  http_code=$(echo "$response" | tail -n1)
  body=$(echo "$response" | sed '$d')

  if [ "$http_code" != "200" ]; then
    echo "Error $http_code: $body"
  fi
  ```
</CodeGroup>

## Retry Strategy

For transient errors (429, 500, 503), implement exponential backoff:

```python theme={"dark"}
import time
import random

def retry_with_backoff(func, max_retries=5, base_delay=1):
    for attempt in range(max_retries):
        try:
            return func()
        except Exception as e:
            if attempt == max_retries - 1:
                raise

            # Check if retryable
            if hasattr(e, 'status_code') and e.status_code in [429, 500, 503]:
                delay = base_delay * (2 ** attempt) + random.uniform(0, 1)
                print(f"Attempt {attempt + 1} failed. Retrying in {delay:.1f}s...")
                time.sleep(delay)
            else:
                raise
```

## Debugging Tips

<AccordionGroup>
  <Accordion title="Log request and response details">
    Include request ID, timestamp, and full error response in logs for debugging.
  </Accordion>

  <Accordion title="Check the param field">
    The `param` field tells you exactly which field caused validation errors.
  </Accordion>

  <Accordion title="Verify API key format">
    Keys must start with `mvra_live_` and be exactly as copied from the dashboard.
  </Accordion>

  <Accordion title="Test with curl first">
    Isolate issues by testing the raw API with curl before debugging SDK code.
  </Accordion>
</AccordionGroup>

## Request IDs

Some error responses include a `request_id` (or similar) in the response headers or body. If present, include it when contacting support—it helps us locate the exact request in our logs.

```
X-Request-ID: req_abc123xyz
```

Log this value in your application when errors occur. Example:

```python theme={"dark"}
# If the API returns X-Request-ID in headers
request_id = response.headers.get("X-Request-ID")
if not response.ok and request_id:
    log_error(f"Request failed: {request_id} - {response.text}")
```

## Logging for Support

When reporting issues, provide structured information. **Never log or share your full API key**—only the prefix (e.g. `mvra_live_abcd...`).

| Field           | Include                                    |
| --------------- | ------------------------------------------ |
| Error `code`    | From `error.code`                          |
| Error `message` | From `error.message`                       |
| `param`         | From `error.param` (for validation errors) |
| HTTP status     | e.g. 401, 402, 429                         |
| Endpoint        | e.g. `/responses`                          |
| Timestamp       | When the error occurred                    |
| Request ID      | If returned in headers                     |
| API key prefix  | First 10 characters only                   |

For production error handling patterns, see [Error Handling Patterns](/cookbooks/error-handling-patterns).

## Getting Help

If you encounter persistent errors:

1. Check our [status page](https://status.mavera.io) for outages
2. Review the error message and code
3. Contact [support@mavera.io](mailto:support@mavera.io) with:
   * Error message and code
   * Request details (endpoint, parameters)
   * Timestamp
   * Request ID (if available)
   * Your API key prefix (first 10 characters only)

<CardGroup cols={2}>
  <Card title="Error Handling Patterns" icon="code" href="/cookbooks/error-handling-patterns">
    Retries, backoff, user-facing messages
  </Card>

  <Card title="Authentication" icon="key" href="/guides/authentication">
    Fix 401 errors
  </Card>

  <Card title="Rate Limits" icon="gauge" href="/guides/rate-limits">
    Handle 429
  </Card>

  <Card title="Credits" icon="coins" href="/guides/credits">
    Handle 402
  </Card>
</CardGroup>
