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

# Errors

> Success is any 2xx. Errors use the HTTP status, a readable message and, where your code should branch, a stable code.

```json theme={null}
{
  "error": "Insufficient wallet balance",
  "code": "INSUFFICIENT_BALANCE"
}
```

Branch on the HTTP status and `code`. The `error` text is written for people and may change.

| Status | Code | Meaning | What to do |
| - | - | - | - |
| `400` | | Something is missing or a value is invalid; the message says which. | Fix the request. Don't retry it unchanged. |
| `400` | `ALL_OPTED_OUT` | Everyone on the campaign has opted out. | Change the audience. |
| `401` | | No API key, or it's wrong, disabled or expired. | Check the key in **Settings → API keys**. |
| `402` | `INSUFFICIENT_BALANCE` | Your wallet doesn't cover this send. | Top up, then retry. |
| `403` | | The key lacks the scope, is used from an IP that isn't on its allowlist, or the feature isn't enabled for your account. | Use a key with the right scope, from an allowed IP. |
| `403` | `VERIFICATION_REQUIRED` | Your account must be verified before sending. | Finish verification in the dashboard. |
| `404` | | Nothing with that ID in your account. | Check the ID. |
| `409` | | A precondition isn't met, for example WhatsApp isn't connected. | Set it up, then retry. |
| `409` | `IDEMPOTENCY_IN_PROGRESS` | A request with the same `Idempotency-Key` is still running. | Wait a second, then retry. |
| `422` | `IDEMPOTENCY_KEY_REUSED` | The `Idempotency-Key` was already used for a different request. | Use a new key for a new operation. |
| `429` | | Over the key's request limit. | Wait `Retry-After` seconds. See [Rate limits](https://docs.telaven.com/get-started/rate-limits.md). |
| `500` | | Unexpected error on our side. | Retry with backoff. |
| `503` | | A provider isn't configured or is unavailable. | Retry later. |

## Retrying safely

Only retry `429`, `500` and `503`, waiting longer each time.

> [!TIP]
>
> Add an [`Idempotency-Key`](https://docs.telaven.com/get-started/requests-and-responses#idempotency) header to every `POST` you retry, and keep it the same across retries. If the first attempt went through, you get its response back instead of a second SMS.

```javascript Node.js theme={null}
async function telaven(path, init = {}, tries = 4) {
  // One key per operation, reused on every retry of it.
  const idempotencyKey = crypto.randomUUID();
  for (let i = 0; ; i++) {
    const res = await fetch(`https://app.telaven.com/api/v1${path}`, {
      ...init,
      headers: {
        Authorization: `Bearer ${process.env.TELAVEN_API_KEY}`,
        "Content-Type": "application/json",
        ...(init.method === "POST" ? { "Idempotency-Key": idempotencyKey } : {}),
        ...init.headers,
      },
    });
    const body = await res.json().catch(() => ({}));
    if (res.ok) return body;
    const retryable = res.status === 429 || res.status >= 500;
    if (!retryable || i === tries - 1) {
      throw Object.assign(new Error(body.error ?? res.statusText), {
        status: res.status,
        code: body.code,
      });
    }
    const wait = Number(res.headers.get("Retry-After")) || 2 ** i;
    await new Promise((r) => setTimeout(r, wait * 1000));
  }
}
```

```python Python theme={null}
import os, time, uuid, requests

def telaven(method, path, tries=4, **kw):
    headers = {"Authorization": f"Bearer {os.environ['TELAVEN_API_KEY']}"}
    if method == "POST":
        headers["Idempotency-Key"] = str(uuid.uuid4())  # same key on every retry
    for i in range(tries):
        res = requests.request(
            method,
            f"https://app.telaven.com/api/v1{path}",
            headers=headers,
            timeout=30,
            **kw,
        )
        if res.ok:
            return res.json()
        retryable = res.status_code == 429 or res.status_code >= 500
        if not retryable or i == tries - 1:
            body = res.json() if res.content else {}
            raise RuntimeError(f"{res.status_code} {body.get('code', '')}: {body.get('error')}")
        time.sleep(float(res.headers.get("Retry-After", 2 ** i)))
```

```csharp C# theme={null}
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

var http = new HttpClient { BaseAddress = new Uri("https://app.telaven.com/api/v1/") };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
    "Bearer", Environment.GetEnvironmentVariable("TELAVEN_API_KEY"));

using var sent = await SendWithRetry(http, HttpMethod.Post, "sms/send",
    new { to = new[] { "0712345678" }, message = "Your order has shipped." });
Console.WriteLine(sent.RootElement);

static async Task<JsonDocument> SendWithRetry(
    HttpClient http, HttpMethod method, string path, object? body = null, int tries = 4)
{
    // One key per operation, reused on every retry of it.
    var idempotencyKey = Guid.NewGuid().ToString();
    for (var i = 0; ; i++)
    {
        // A request message can only be sent once: build a new one for each attempt.
        using var request = new HttpRequestMessage(method, path);
        if (body is not null)
            request.Content = new StringContent(
                JsonSerializer.Serialize(body), Encoding.UTF8, "application/json");
        if (method == HttpMethod.Post)
            request.Headers.Add("Idempotency-Key", idempotencyKey);

        using var response = await http.SendAsync(request);
        var json = await response.Content.ReadAsStringAsync();
        if (response.IsSuccessStatusCode)
            return JsonDocument.Parse(json);

        var status = (int)response.StatusCode;
        var retryable = status is 429 or 500 or 503;
        if (!retryable || i == tries - 1)
            throw new HttpRequestException($"{status}: {json}", null, response.StatusCode);

        var wait = response.Headers.RetryAfter?.Delta ?? TimeSpan.FromSeconds(Math.Pow(2, i));
        await Task.Delay(wait);
    }
}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.