# Errors (/errors)

Every failure has a stable code to branch on and says whether to retry. The codes and their HTTP statuses are the same for both APIs.

A failed request answers with an `error` object and no `data`:

```json title="Response · 400"
{
  "error": {
    "code": "invalid_parameter",
    "message": "origin must be a 3-letter airport code such as SFO.",
    "param": "origin",
    "retry": "never",
    "request_id": "req_41ab9c"
  }
}
```

<TypeTable type={{"code":{"type":"string","description":"Stable. Branch on this. New codes can be added within v1.","required":true},"message":{"type":"string","description":"One sentence, safe to show a person. The wording can change, so never match on it.","required":true},"param":{"type":"string","description":"The field at fault, when there is one."},"retry":{"type":"\"never\" | \"now\" | \"after\"","description":"Whether the same request can succeed. See below.","required":true},"retry_after_s":{"type":"integer","description":"Seconds to wait, when retry is after. Also in the Retry-After header."},"request_id":{"type":"string","description":"Names this request. Quote it when you ask for help.","required":true}}} />

## What to do [#what-to-do]

One rule covers every code:

- **`never`:** the same request will fail again. Change the request, or stop.
- **`now`:** an immediate retry can succeed. Retry once or twice, with a short pause.
- **`after`:** wait `retry_after_s` seconds, then retry.

Finding nothing is not an error. A search with no results is a success, with an empty list.

## Codes [#codes]

Each code always comes with the same HTTP status.

| Status | `code` | When | `retry` |
| --- | --- | --- | --- |
| 400 | `invalid_parameter` | A field is missing, malformed or out of range. `param` names it. | `never` |
| 400 | `invalid_body` | A POST body is not a JSON object, or is over 16 KB. | `never` |
| 401 | `unauthenticated` | No key, or a key we don't know. | `never` |
| 403 | `forbidden` | The key may not do this: it is revoked or expired, lacks live access or this product, or was used from outside your networks. A booking link that was changed also answers this. | `never` |
| 404 | `not_found` | Nothing at this address. | `never` |
| 404 | `search_not_found` | No search with that id for this key. Search again. | `never` |
| 405 | `method_not_allowed` | The address exists, but not for this method. The `Allow` header lists the methods it answers. | `never` |
| 410 | `gone` | A booking link has expired. | `never` |
| 429 | `rate_limited` | Over one of your [limits](/rate-limits). | `after` |
| 502 | `supplier_error` | The supplier failed the search. | `now` |
| 503 | `search_capacity` | No capacity to start new searches just now. Recent searches still answer. | `after` |
| 503 | `service_unavailable` | Keys or limits can't be checked just now. | `after` |
| 504 | `supplier_timeout` | The supplier took too long. | `now` |
| 500 | `internal_error` | A fault on our side. The detail is logged, never sent. | `now` |

<Callout type="info" title="A failed search stays failed">
If reading a search by its `search_id` answers `supplier_error` or `supplier_timeout`, that search is over. Reading it again gives the same error. `retry: "now"` there means search the trip again.
</Callout>

## Handle errors in code [#handle-errors-in-code]

Branch on `error.retry`, not on the status or the message:

<Tabs items={["JavaScript","Python"]}>
<Tab value="JavaScript">
```js title="call.mjs"
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

export async function call(url, init = {}, attempts = 3) {
  for (let attempt = 1; ; attempt += 1) {
    const response = await fetch(url, {
      ...init,
      headers: { ...init.headers, "X-API-Key": process.env.VOYAGE_LABS_API_KEY },
    });
    const body = await response.json();
    if (response.ok) return body;

    const { code, message, retry, retry_after_s, request_id } = body.error;
    if (retry === "never" || attempt >= attempts) {
      throw new Error(`${code}: ${message} (request ${request_id})`);
    }
    await sleep(retry === "after" ? (retry_after_s ?? 1) * 1000 : 500 * attempt);
  }
}
```
</Tab>

<Tab value="Python">
```python title="call.py"
import os
import time
import requests

def call(method, url, attempts=3, **kwargs):
    headers = {**kwargs.pop("headers", {}), "X-API-Key": os.environ["VOYAGE_LABS_API_KEY"]}
    for attempt in range(1, attempts + 1):
        response = requests.request(method, url, headers=headers, timeout=40, **kwargs)
        body = response.json()
        if response.ok:
            return body

        error = body["error"]
        if error["retry"] == "never" or attempt == attempts:
            raise RuntimeError(f"{error['code']}: {error['message']} (request {error['request_id']})")
        if error["retry"] == "after":
            time.sleep(error.get("retry_after_s", 1))
        else:
            time.sleep(0.5 * attempt)
```
</Tab>
</Tabs>

## Asking for help [#asking-for-help]

Every answer, success or failure, carries a request id in `meta.request_id` or `error.request_id`, and in the `X-Request-Id` header. Log it. With it, we can find the exact request.