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

# Error handling

> The SDK error classes, the fields they carry and how to handle authentication, validation, rate limit and billing.

Every error the API returns as an HTTP response is thrown as `RoutaApiError` or one of its subclasses. They all carry:

| Field | Description |
| - | - |
| `code` | Stable error code, such as `channel_inactive`. See [Error codes](https://docs.routa.chat/en/errors/error-codes.md). |
| `statusCode` | HTTP status of the response. |
| `requestId` | Request ID. Quote it when you contact support. |
| `type` | Category of the error in the API, such as `billing_error` or `conflict_error`. It is `undefined` when the response did not come from the API, such as one from a proxy. Available from 0.3.0. |
| `details` | Machine-readable values some errors carry, such as `limit` and `used`. It is `undefined` when the error sets none. Available from 0.3.0. |
| `docUrl` | Link to the documentation of the error, when the API sent one. |
| `message` | Error text, in English. |

## Error classes

| HTTP status | Class | Extra fields |
| - | - | - |
| `401` | `RoutaAuthenticationError` | n/a |
| `402` | `RoutaBillingError` | `limit`, `used` and `resetsAt`, each only on the codes that set it |
| `403`, `404`, `422` | `RoutaInvalidRequestError` | `param`: the request field at fault, with the API names, when known |
| `409` | `RoutaConflictError` | `reason`: what blocks the operation, when the API sent it |
| `429` | `RoutaRateLimitError` | `retryAfter`: seconds to wait, when the server sent it |
| Any other (`413`, `5xx`…) | `RoutaApiError` | n/a |

`RoutaBillingError` and `RoutaConflictError` exist from 0.3.0. Both extend `RoutaApiError`, so a `catch` on `RoutaApiError` still catches these errors.

```ts theme={null}
import {
  RoutaApiError,
  RoutaAuthenticationError,
  RoutaBillingError,
  RoutaConflictError,
  RoutaInvalidRequestError,
  RoutaRateLimitError,
} from '@routa-chat/sdk'

try {
  await routa.messages.send({
    channel: 'chan_...',
    to: '+5581999999999',
    text: 'Hi!',
  })
} catch (error) {
  if (error instanceof RoutaAuthenticationError) {
    // Missing, invalid or revoked key. Trying again does not help.
  } else if (error instanceof RoutaRateLimitError) {
    console.warn(`Rate limited; retry in ${error.retryAfter ?? '?'}s`)
  } else if (error instanceof RoutaBillingError) {
    console.error(`Billing refusal (${error.code}): used ${error.used ?? '?'} of ${error.limit ?? '?'}`)
  } else if (error instanceof RoutaConflictError) {
    console.error(`Conflict (${error.code}): ${error.reason ?? 'n/a'}`)
  } else if (error instanceof RoutaInvalidRequestError) {
    console.error(`Rejected (${error.code}) on field ${error.param ?? 'n/a'}: ${error.message}`)
  } else if (error instanceof RoutaApiError) {
    console.error(error.statusCode, error.code, error.requestId)
  } else {
    throw error
  }
}
```

> [!NOTE]
>
> A subclass is also a `RoutaApiError`. Test the most specific subclasses first, as in the example above.

## Handling business cases

Use the `code` to decide what to do, not the message text.

```ts theme={null}
try {
  await routa.messages.send(params)
} catch (error) {
  if (!(error instanceof RoutaApiError)) throw error

  switch (error.code) {
    case 'message_quota_exceeded':
      // 402: the allowance for the period is used up. Queue on your side and tell the team.
      break
    case 'channel_inactive':
    case 'template_not_approved':
      // 422: fix the setup before you try again.
      break
    case 'invalid_recipient':
      // 422: the number does not exist. Mark the contact as invalid.
      break
    default:
      throw error
  }
}
```

> [!WARNING]
>
> Do not schedule automatic retries for a `402`: waiting does not increase the allowance. The SDK does not retry it either. See [Plans and allowance](https://docs.routa.chat/en/billing/plans-and-quota.md).

## Malformed requests and reasons

A `422` with the `request_invalid` code means the request does not have the documented format: a field is missing or has the wrong type, which can happen with values that reach the SDK untyped. `param` is the field, with the API names (`template.button_parameters.0.index`), and is `undefined` when none can be pointed at.

`details` carries what a program can use, with keys that depend on the `code`. In several errors, `details.reason` tells apart the causes behind one code. Check the type of the value before you use it:

```ts theme={null}
import { RoutaInvalidRequestError } from '@routa-chat/sdk'

try {
  await routa.templates.submit({
    channel: 'chan_...',
    name: 'order_shipped',
    language: 'en_US',
    category: 'utility',
    bodyText: 'Your order {{1}} has shipped.',
    variableExamples: [],
  })
} catch (error) {
  if (error instanceof RoutaInvalidRequestError && error.code === 'template_variables_invalid') {
    // "variable_examples", "body_examples_count_mismatch", 1
    console.error(error.param, error.details?.['reason'], error.details?.['expected'])
  } else {
    throw error
  }
}
```

See the values in [Reasons for each code](https://docs.routa.chat/en/errors/error-codes.md#reasons-for-each-code).

## Billing errors

A `402` arrives as a `RoutaBillingError`. Use the `code` to tell the cases apart. The numbers only exist on the codes that set them, and are `undefined` on the others.

| `code` | Fields filled in |
| - | - |
| `free_messages_exhausted` | `limit` and `used` |
| `message_quota_exceeded` | `limit`, `used` and `resetsAt` (ISO 8601, when the allowance resets) |
| `project_limit_exceeded`, `channel_limit_exceeded` | `limit` |
| `subscription_required`, `payment_failed` | none |

```ts theme={null}
import { RoutaBillingError } from '@routa-chat/sdk'

try {
  await routa.messages.send(params)
} catch (error) {
  if (!(error instanceof RoutaBillingError)) throw error

  if (error.code === 'message_quota_exceeded') {
    // Queue on your side and send again after `error.resetsAt`.
    console.warn(`Allowance used up: ${error.used}/${error.limit}, resets at ${error.resetsAt}`)
  } else {
    // The free allowance ran out, or a subscription or payment is missing. Tell the team.
    console.error(error.code, error.requestId)
  }
}
```

A test project is not refused for billing when it sends messages.

## Conflicts

A `409` arrives as a `RoutaConflictError`. When the API says so, `reason` tells what blocks the operation. Today this applies to `project_not_deletable` in the [Partner API](https://docs.routa.chat/en/sdk/partner.md), with `has_enabled_channel` or `last_project`. The idempotency conflicts (`idempotency_key_reuse` and `idempotency_in_progress`) are also `409`. See [Idempotency](https://docs.routa.chat/en/reliability/idempotency.md).

## What the SDK already retries

Network failures, `429`, `5xx` and a `409 idempotency_in_progress` are retried automatically, up to `maxRetries` times. Only the final error reaches your `catch`. `401`, `402`, `403`, `404` and `422` are never retried, and no `409` other than `idempotency_in_progress` is retried. See [Configuration](https://docs.routa.chat/en/sdk/configuration.md#retries).

## What is not a `RoutaApiError`

Two situations do not go through these classes:

* **Network failures and timeouts**, once the retries run out, reject with a plain `Error` whose `name` is `'HttpRequestError'`. The class is not exported yet, so check `error.name` instead of using `instanceof`.
* **Invalid configuration**, such as an empty `apiKey`, throws a plain synchronous `Error` in the `Routa` constructor.

```ts theme={null}
try {
  await routa.messages.send(params)
} catch (error) {
  if (error instanceof Error && error.name === 'HttpRequestError') {
    // The network failed after every retry. The message may or may not have been created:
    // repeat with the same idempotencyKey.
  }
}
```

> [!NOTE]
>
> A `413` (body too large on a [media](https://docs.routa.chat/en/sdk/media.md) upload) arrives as a base `RoutaApiError`, with `statusCode` `413`, and is not retried.

## Delivery failures

A provider failure does **not** become an exception in `messages.send()`: the message is accepted and the failure shows up later, asynchronously, as the `message.failed` event. The `RoutaProviderError` class exists for future use, and no code in the SDK throws it today.


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