# Errors

Every status the Insurge API answers with, the shape of its body, and what your code should do about it.

The API uses HTTP status codes: `2xx` worked, `4xx` means the request needs changing, and `5xx` means try again later. Error bodies are JSON with a `detail` field, except a `416`, which has no body, and some `5xx`. Branch on the status first, then on `detail` when you need the reason.

## Error bodies

`detail` comes in three shapes.

**A sentence.** Most errors. Show it in your logs; don't match on its exact words.

```json title="403 Forbidden"
{
  "detail": "API key is missing scope: transcripts:read"
}
```

**A code and a message.** Only when a [continue link](/docs/developers/api/continue-links) can't be made. Branch on `code`.

```json title="422 Unprocessable Entity"
{
  "detail": {
    "code": "anonymous_lead",
    "message": "The visitor never said who they are, so there is no one to resume."
  }
}
```

**A list of problems.** When a parameter or body field is missing or out of range. `loc` says where the problem is, and `msg` what is wrong.

```json title="422 Unprocessable Entity"
{
  "detail": [
    {
      "type": "greater_than_equal",
      "loc": ["query", "limit"],
      "msg": "Input should be greater than or equal to 1",
      "input": "0",
      "ctx": { "ge": 1 }
    }
  ]
}
```

A sturdy client reads all three:

**Node.js**

```js title="Read any error body"
function errorText(status, body) {
  const d = body?.detail;
  if (typeof d === "string") return `${status}: ${d}`;
  if (Array.isArray(d)) return `${status}: ${d.map((e) => `${e.loc.join(".")} ${e.msg}`).join("; ")}`;
  if (d && d.code) return `${status} ${d.code}: ${d.message}`;
  return `${status}`;
}
```

**Python**

```python title="Read any error body"
def error_text(status: int, body: dict) -> str:
    d = body.get("detail")
    if isinstance(d, str):
        return f"{status}: {d}"
    if isinstance(d, list):
        return f"{status}: " + "; ".join(
            ".".join(map(str, e["loc"])) + " " + e["msg"] for e in d
        )
    if isinstance(d, dict) and "code" in d:
        return f"{status} {d['code']}: {d['message']}"
    return str(status)
```

## Status codes

| Status | What it means | What to do |
|---|---|---|
| `200` | It worked. | |
| `206` | Part of a recording, for a `Range` request. | Write the bytes at the offset you asked for. |
| `400` | The request can't be read: a `cursor` the API didn't give you, or a `sha256` that isn't 64 hex characters. | Fix the value. Don't retry as is. |
| `401` | The key is missing, wrong, expired or revoked. | Check the header and the key. If it expired or was revoked, [create a new key](/docs/integrations/api-keys). |
| `403` | The key works but doesn't have the scope this endpoint needs. | Create a key with that access switched on. Scopes can't be added to an existing key. |
| `404` | Nothing with that id in your workspace, a test meeting, or a recording that isn't ready to download. | Check the id and that the key belongs to the right workspace. Don't retry. |
| `405` | The path exists but not with this method. | Check the method. |
| `409` | It conflicts with the current state: a recording still being processed, a visitor who already finished. | Wait for the matching webhook, or decide again from the current state. |
| `412` | The `sha256` you sent doesn't match the stored recording. Nothing was deleted. | Download again and compare before deleting. |
| `416` | The `Range` can't be satisfied, for example it starts past the end of the file. The answer has no body. | Ask for a range within the size in `Content-Range`. |
| `422` | A parameter or field is missing or out of range, or a continue link can't be made. | Fix the request. For continue links, branch on `detail.code`. |
| `429` | Too many requests for this key, or too many recording downloads at once. | Wait the number of seconds in `Retry-After`, then try again. |
| `500` | Something went wrong at Insurge. The body may not be JSON. | Retry with backoff. If it keeps failing, tell your Insurge contact the time and the path. |
| `502`, `504` | Insurge was briefly unreachable, for example during an update. | Retry with backoff. |
| `503` | Insurge couldn't finish the request at that moment, for example `database read timed out, retry shortly` or `Recording temporarily unavailable`. | Retry with backoff. |

## The messages you'll see

| Status | `detail` |
|---|---|
| `400` | `cursor is not one this API returned.` |
| `400` | `sha256 must be 64 hexadecimal characters.` |
| `401` | `Missing API key.` |
| `401` | `Invalid, expired or revoked API key.` |
| `403` | `API key is missing scope: <scope>` |
| `404` | `Lead not found: <id>`, `Meeting not found: <id>` |
| `404` | `Recording not ready`, `Recording file not found`, `This meeting has no stored recording.` |
| `404` | `Not Found`: no such path. Check it starts with `/api/v1`. |
| `409` | `The recording is still being processed.`, `The recording changed while it was being deleted.` |
| `412` | `sha256 does not match the stored recording; nothing was deleted.` |
| `422` | `status must be 'all' or a comma-separated list of: …` (listing recordings) |
| `429` | `Rate limit exceeded for this API key.` |
| `429` | `At most 4 recording downloads at once per workspace. Retry when one finishes.` |
| `503` | `The recording could not be deleted. Try again.` |

Continue-link codes (`no_meeting`, `already_completed`, `test_meeting`, `anonymous_lead`, `not_resumable`, `no_link`) are explained on [Continue links](/docs/developers/api/continue-links#when-a-link-cant-be-made).

## Retrying safely

Retry `429`, `500`, `502`, `503` and `504`. Don't retry other `4xx` answers unchanged: they fail the same way again.

- On `429`, wait at least `Retry-After` seconds.
- Otherwise wait longer after each try, for example 1, 2, 4, 8 and 16 seconds with some randomness, and stop after a few tries.
- Every `GET` and `DELETE` is safe to repeat. Deleting a recording twice answers `200` the second time, and ending continue links twice answers `{"revoked": 0}`.
- `POST /api/v1/integrations/sync/{meeting_id}` is safe to repeat: it updates the record it wrote before.
- `POST /api/v1/resume-links` makes a new link each time. A repeat leaves you with two working links; [end](/docs/developers/api/continue-links#end-continue-links) the one you don't use.

**Node.js**

```js title="Retry with backoff"
const RETRY = new Set([429, 500, 502, 503, 504]);

async function insurge(path, init = {}, tries = 5) {
  for (let attempt = 0; ; attempt++) {
    const res = await fetch(`https://api.insurgeai.com${path}`, {
      ...init,
      headers: { ...init.headers, Authorization: `Bearer ${process.env.INSURGE_API_KEY}` },
    });
    if (res.ok || !RETRY.has(res.status) || attempt + 1 >= tries) return res;
    const after = Number(res.headers.get("retry-after"));
    const wait = after > 0 ? after * 1000 : 2 ** attempt * 1000 * (0.5 + Math.random());
    await new Promise((r) => setTimeout(r, wait));
  }
}
```

**Python**

```python title="Retry with backoff"
import os
import random
import time

import requests

RETRY = {429, 500, 502, 503, 504}


def insurge(method: str, path: str, tries: int = 5, **kwargs) -> requests.Response:
    headers = {"Authorization": f"Bearer {os.environ['INSURGE_API_KEY']}"}
    for attempt in range(tries):
        r = requests.request(
            method, f"https://api.insurgeai.com{path}", headers=headers, timeout=30, **kwargs
        )
        if r.ok or r.status_code not in RETRY or attempt + 1 == tries:
            return r
        after = r.headers.get("Retry-After")
        wait = int(after) if after and after.isdigit() else 2**attempt * (0.5 + random.random())
        time.sleep(wait)
    return r
```
