> Source: https://developers.terrawallet.us/docs/errors . Terra Wallet developer docs (early access).

# Errors

Every error from the Terra API has the same shape, the right HTTP status and a stable `code` you can switch on.

> **Preview.** The API is in early access. Codes are stable once published, but new ones may be added.

## The error envelope

```json
{
  "error": {
    "code": "INSUFFICIENT_SCOPE",
    "message": "This key does not have the scope this route needs.",
    "requestId": "req_..."
  }
}
```

- `code` is stable and in `SNAKE_CASE`. Write your logic against it, never against `message`.
- `message` is for people. It may change wording at any time.
- `requestId` identifies the request. Include it when you contact support.
- Some errors add a field: `param` names the field that failed validation, and a `429` carries `retryAfter`
  (seconds).
- Errors never echo your input and never contain stack traces. Ignore fields you do not know: new ones may be
  added.

## Request ids

Every response carries an `X-Request-Id` header. You may send your own id in `X-Request-Id`; Terra uses it if it
matches `^[A-Za-z0-9_-]{8,64}$`, so you can trace one request across your logs and Terra's.

## Common codes

These are the codes the v1 contract defines and the platform returns today. The full list for each route is in
the [API reference](https://developers.terrawallet.us/docs/reference.md) and the exported OpenAPI document.

| Status | Code | What it means | What to do |
|---|---|---|---|
| 400 | `VALIDATION_FAILED` | A field is missing, has the wrong type, is over its cap, or is not allowed | Fix the field named in `param` |
| 400 | `IDEMPOTENCY_KEY_REQUIRED` | A create without an `Idempotency-Key` header | Send one; see [Idempotency](https://developers.terrawallet.us/docs/idempotency.md) |
| 400 | `IDEMPOTENCY_KEY_INVALID` | The `Idempotency-Key` is not 8 to 128 printable characters | Use a key of 8 to 128 printable characters |
| 401 | `INVALID_API_KEY` | The key is malformed, unknown, expired or revoked | Check which key your server loads; rotate it if it leaked |
| 401 | `UNAUTHENTICATED` | No valid dashboard session (dashboard routes) | Sign in again |
| 403 | `INSUFFICIENT_SCOPE` | The key lacks the scope the route needs | Create a key with the right scopes |
| 403 | `LIVE_DISABLED` | A live-mode action while live mode is not enabled | Use test mode, or wait until live mode is enabled for you |
| 403 | `PRODUCT_DISABLED` | The product behind this route is switched off | Check the product's status before you build on it |
| 403 | `METHOD_DISABLED` | A sign-up or sign-in method that is switched off | Use another method (dashboard only) |
| 404 | `NOT_FOUND` | The object does not exist, or it belongs to another organization | Check the id and the key's environment |
| 409 | `IDEMPOTENCY_KEY_REUSED` | The same `Idempotency-Key` was sent with a different body | Use a new key for a new request; see [Idempotency](https://developers.terrawallet.us/docs/idempotency.md) |
| 409 | `IDEMPOTENCY_IN_PROGRESS` | The first request with this key is still running | Wait a moment, then retry with the same key |
| 413 | `PAYLOAD_TOO_LARGE` | The request body is over the size cap | Send less data |
| 415 | `UNSUPPORTED_MEDIA_TYPE` | The body is not JSON | Send `Content-Type: application/json` |
| 429 | `RATE_LIMITED` | Too many requests for this key or organization | Back off and retry; see [Rate limits](https://developers.terrawallet.us/docs/rate-limits.md) |
| 503 | `MAINTENANCE` | Platform maintenance | Retry later. `/v1/auth/*` and `/v1/me` stay available |

**Provider errors are never zeros.** When a chain data provider cannot be reached, the API returns an error such
as `PROVIDER_UNAVAILABLE` instead of a false zero balance or a missing payment. Retry later; never treat it as
"not paid".

**Validation errors.** A request with unknown fields, wrong types or strings over their caps is rejected with
`400 VALIDATION_FAILED`, and `param` names the field when there is one. The schemas are strict on purpose: a
request can never set a field it does not own.

**Another organization's objects** return `404 NOT_FOUND`, exactly like an id that does not exist.

## Handling errors well

1. Switch on `error.code`, not on the HTTP status alone.
2. Retry only what is safe to retry: `429`, `503`, `409 IDEMPOTENCY_IN_PROGRESS`, network errors and timeouts.
   Always reuse the same `Idempotency-Key` on a retried create.
3. Do not retry `400`, `401`, `403`, `404` or `409 IDEMPOTENCY_KEY_REUSED` without changing the request.
4. Log `requestId` and the `X-Request-Id` header, never the `Authorization` header.

```js
// Preview: a small error helper for the Terra API (Node 18 or later).
async function terraFetch(path, init = {}) {
  const res = await fetch(`https://terrawallet.us/api/v1${path}`, {
    ...init,
    headers: {
      Authorization: `Bearer ${process.env.TERRA_SECRET_KEY}`,
      "Content-Type": "application/json",
      ...init.headers,
    },
  });
  const body = await res.json().catch(() => null);
  if (!res.ok) {
    const err = new Error(body?.error?.message ?? `Terra API error ${res.status}`);
    err.status = res.status;
    err.code = body?.error?.code ?? null;
    err.requestId = body?.error?.requestId ?? res.headers.get("X-Request-Id");
    throw err;
  }
  return body;
}
```
