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

# Handling Dolva API Errors: Auth, Validation, and More

> Learn how to handle Dolva API errors including 401 authentication failures, 422 validation errors, and network issues in your integration.

Dolva returns standard HTTP status codes to indicate success or failure. Building robust error handling into your integration ensures that failures degrade gracefully rather than crashing your application.

## HTTP Status Codes

| Status                      | Meaning               | Common Cause                                 |
| --------------------------- | --------------------- | -------------------------------------------- |
| `200 OK`                    | Request succeeded     | —                                            |
| `401 Unauthorized`          | Authentication failed | Missing or invalid Bearer token              |
| `403 Forbidden`             | Access denied         | Token valid but lacks required permissions   |
| `422 Unprocessable Entity`  | Validation error      | Missing `audio` field or invalid file format |
| `500 Internal Server Error` | Server error          | Transient issue — retry with backoff         |

## Validation Errors (422)

When your request is missing required fields or contains invalid data, Dolva returns a `422` response with a detailed error body:

```json 422 Validation Error theme={null}
{
  "detail": [
    {
      "loc": ["body", "audio"],
      "msg": "field required",
      "type": "value_error.missing"
    }
  ]
}
```

Each item in `detail` describes one validation failure:

* **`loc`** — where the error occurred (e.g., `["body", "audio"]` means the `audio` field in the request body is the problem)
* **`msg`** — a human-readable description of the error
* **`type`** — a machine-readable error type string

**Common 422 causes:**

* The `audio` field is missing from your `multipart/form-data` request
* The file is empty or corrupt
* The content type is not recognized as audio

## Handling Errors in Code

<CodeGroup>
  ```python Python theme={null}
  import requests
  import os
  import time

  def analyze_audio(path, endpoint="cognitive", retries=3):
      token = os.environ["DOLVA_API_TOKEN"]
      url = f"https://api.dolva.ai/v1/analyze/{endpoint}"

      for attempt in range(retries):
          with open(path, "rb") as f:
              resp = requests.post(
                  url,
                  headers={"Authorization": f"Bearer {token}"},
                  files={"audio": f}
              )

          if resp.status_code == 200:
              return resp.json()
          elif resp.status_code == 401:
              raise Exception("Invalid API token. Check your DOLVA_API_TOKEN.")
          elif resp.status_code == 422:
              raise Exception(f"Validation error: {resp.json()}")
          elif resp.status_code >= 500:
              if attempt < retries - 1:
                  time.sleep(2 ** attempt)  # exponential backoff
                  continue
              raise Exception(f"Server error after {retries} attempts: {resp.status_code}")
          else:
              raise Exception(f"Unexpected error {resp.status_code}: {resp.text}")
  ```

  ```javascript Node.js theme={null}
  async function analyzeAudio(filePath, endpoint = "cognitive", retries = 3) {
    const { default: fetch } = await import("node-fetch");
    const { default: FormData } = await import("form-data");
    const fs = await import("fs");

    const token = process.env.DOLVA_API_TOKEN;
    const url = `https://api.dolva.ai/v1/analyze/${endpoint}`;

    for (let attempt = 0; attempt < retries; attempt++) {
      const form = new FormData();
      form.append("audio", fs.createReadStream(filePath));

      const response = await fetch(url, {
        method: "POST",
        headers: { Authorization: `Bearer ${token}`, ...form.getHeaders() },
        body: form,
      });

      if (response.ok) return response.json();

      const body = await response.json().catch(() => ({}));

      if (response.status === 401) throw new Error("Invalid API token.");
      if (response.status === 422) throw new Error(`Validation error: ${JSON.stringify(body)}`);
      if (response.status >= 500 && attempt < retries - 1) {
        await new Promise((r) => setTimeout(r, 2 ** attempt * 1000));
        continue;
      }
      throw new Error(`Request failed with status ${response.status}`);
    }
  }
  ```
</CodeGroup>

## Retrying on Server Errors

For `5xx` errors, implement exponential backoff: wait 1s before the first retry, 2s before the second, 4s before the third, and so on. Most transient server errors resolve within a few seconds.

<Warning>Do NOT retry `401` or `422` errors — these indicate problems with your request that won't resolve on their own. Fix the underlying issue before retrying.</Warning>

## Checking API Health

Before sending large batches of requests, you can verify that the Dolva API is reachable by calling the health endpoint (no authentication required):

```bash curl theme={null}
curl https://api.dolva.ai/health
```

A `200 OK` response confirms the API is up. See the [Health endpoint reference](/api-reference/health) for details.

<CardGroup cols={2}>
  <Card title="Authentication" icon="key" href="/authentication">
    Troubleshoot 401 errors and token setup.
  </Card>

  <Card title="Health Endpoint" icon="heart-pulse" href="/api-reference/health">
    Check API availability before batch operations.
  </Card>
</CardGroup>
