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

# Errors

> The error classes the SDK throws, and which one reaches you from where.

The SDK has one error class per failure domain, so `instanceof` tells you what went wrong without parsing a message. For the practical pattern, see [Handling errors](https://docs.cloak.chat/guides/handling-errors.md).

```ts theme={null}
import {
  CloakActionError,
  CloakClientError,
  CloakEnvironmentError,
  CloakRestError,
  CloakEmbedError,
  CloakComponentError,
  CloakWebhookError,
} from '@cloak-software/bot-sdk';
```

| Class | Means | Reaches you as |
| - | - | - |
| `CloakActionError` | The server denied an action. | A rejected promise from the call. |
| `CloakClientError` | The SDK's own plumbing failed, or an interaction was answered twice. | The [`error`](https://docs.cloak.chat/api-reference/events#error) event, or a rejected second response. |
| `CloakEnvironmentError` | The host is wrong, not your bot. | A rejected promise, usually from `login()` or the audio path. |
| `CloakRestError` | An HTTP leg of the REST lane failed. | A rejected promise from `client.rest.*`. |
| `CloakEmbedError` | A card was refused locally, before the wire. | A rejected promise from `sendCard()`, `editCard()`, `createForumPost()`, or `Interaction.ephemeral()`. |
| `CloakComponentError` | A component row or modal was refused locally, before the wire. | A rejected promise from the same calls, plus `Interaction.showModal()`. |
| `CloakWebhookError` | A webhook POST failed. | A rejected promise from `webhooks.post()` or `sendEmbed()`. |

> [!NOTE]
>
> A denied `send()` is none of these. It arrives on the [`sendRejected`](#denied-sends) event, because `send()` is fire-and-forget.

## CloakActionError

The typed rejection for an awaited action the server refused.

```ts theme={null}
class CloakActionError extends Error {
  readonly opcode: number;
  readonly code: number;
  readonly permission?: PermissionName;
}
```

**message** `string`

A human-readable explanation, for example `missing the kick-members permission` or `ban reason too long (max 256 chars)`. This is the stable field to show or log.

**permission** `PermissionName | undefined`

The named permission the bot was denied on, when the failure maps to one. Deleting another member's message without `message_manage` sets this to `'message_manage'`. It is `undefined` when the failure does not map to a named permission, so always fall back to `message`.

**opcode** `number`

A raw numeric diagnostic identifying the action. For logging only.

**code** `number`

A raw numeric diagnostic for the specific failure. For logging only.

> [!WARNING]
>
> Treat `opcode` and `code` as opaque. Branch on `permission`, show `message`, and never hardcode a numeric code.
>
> Three success and error conventions coexist on the Cloak wire, so a raw `code` you read out of a log means different things depending on the action. Messaging actions deny with **negative** codes. Moderation actions deny with **positive** codes 2 and up. The webhook, DM, and REST-credential actions use **`0` as success** with negative errors. A `0` is not universally a failure and a `2` is not universally a success.

### Which calls reject with it

Every awaited action the server can refuse:

* **Message actions**: `react`, `unreact`, `edit`, `delete`, `pin`, `unpin`, `editCard`, in a server channel or (from wire version 3) a DM.
* **Forums**: `createForumPost`, `fetchForumPosts`, `fetchForumMeta`, `editForumPost`, `setForumPostState`, `followForumPost`. See [Forum posts](#forum-posts).
* **Interactions**: `Interaction.ack`, `showModal`, and `ephemeral`, when the server refuses the response. See [Interaction responses](#interaction-responses).
* **Moderation**: `kick`, `ban`, `unban`, `timeout`, `removeTimeout`, `fetchBans`.
* **Channels and groups**: `createChannel`, `editChannel`, `deleteChannel`, `moveChannel`, `createGroup`, `editGroup`, `deleteGroup`.
* **Reads**: `fetchRoles`, `fetchEmojis`, and `fetchMessages` when read history is denied.
* **Direct messages**: `sendDM` and `sendCardDM`, on the create and key-exchange legs. An ineligible target is refused here.
* **Presence**: `setStatus`.
* **Voice**: `joinVoice` and `leaveVoice`.
* **Commands**: `sendCommand`.
* **Webhook CRUD**: `webhooks.list`, `.create`, `.edit`, `.regenerate`, `.delete`.
* **REST**: `client.rest.*`, when the credential mint is refused.

> [!WARNING]
>
> [`fetchMembers`](https://docs.cloak.chat/api-reference/client#fetchmembers) is the exception that catches people out. It does not reject at all against any current backend: the promise never settles, so `try`/`catch` cannot help you and `await` hangs. Do not call it.

> [!NOTE]
>
> `send()`, `sendDM()` after the DM exists, `msg.reply()`, `msg.channel.send()`, `sendTyping()`, and `setAvatar()` are fire-and-forget for delivery. Their promises resolve when the frame goes out. See [Denied sends](#denied-sends).

### When there is no named permission

Some denials are permission-shaped but do not map to one of the 43 [named permissions](https://docs.cloak.chat/api-reference/permissions.md). Pinning is the clearest example: it is gated by a channel-level pin permission that has no name in the vocabulary. `permission` is `undefined` there, and `message` still explains what happened.

```ts theme={null}
try {
  await msg.pin();
} catch (e) {
  if (e instanceof CloakActionError) {
    // e.permission may be undefined here; e.message is always set.
    console.log(e.message);
  }
}
```

### Forum posts

The forum methods reject with negative codes. None of them maps to a named permission, because each verdict folds more than one server-side check, so `permission` is always `undefined` here and `message` is what to show. The capabilities the messages name resolve to ordinary permissions: creating a post is `message_send` on the forum, and managing posts is `message_manage`. See [Forums](https://docs.cloak.chat/guides/forums.md).

> [accordion] createForumPost (opcode 750)
>
> | Code | Meaning |
> | - | - |
> | `-1` | Not authenticated |
> | `-2` | Post creation denied (not a member, or missing the create-posts capability, which resolves to `message_send` on the forum) |
> | `-3` | Bad post title (empty or over the ciphertext cap), or an empty body |
> | `-4` | Tag violation (unknown tag, a moderated tag without the manage-posts capability (`message_manage`), or a required tag missing) |
> | `-5` | This forum is at its post cap |
> | `-6` | Not a forum channel |
> | `-7` | The starter message was denied (send, embed, or poll permission on the forum) |
> | `-8` | Server error while creating the post |

> [accordion] Entering a post (opcode 751)
>
> Issued by the SDK before any action that takes `postId`.
>
> | Code | Meaning |
> | - | - |
> | `-1` | Not authenticated |
> | `-2` | Wrong server selected, or no view permission on the forum |
> | `-3` | No such post under that forum |

> [accordion] fetchForumPosts (opcode 752)
>
> | Code | Meaning |
> | - | - |
> | `-1` | Not authenticated |
> | `-2` | Not a member of that server, or no view permission on the forum |
> | `-3` | Not a forum channel, or a server error while reading the posts |

> [accordion] editForumPost (opcode 754)
>
> | Code | Meaning |
> | - | - |
> | `-1` | Not authenticated |
> | `-2` | Edit denied (not the author, and no manage-posts capability, which resolves to `message_manage`) |
> | `-3` | No such post under that forum |
> | `-4` | Tag violation (unknown tag, a moderated tag without the manage-posts capability (`message_manage`), or a required tag missing) |
> | `-5` | Bad post title (empty or over the ciphertext cap) |

> [accordion] setForumPostState (opcode 755)
>
> | Code | Meaning |
> | - | - |
> | `-1` | Not authenticated |
> | `-2` | State change denied (not the author for this field, and no manage-posts capability, which resolves to `message_manage`) |
> | `-3` | No such post under that forum |
> | `-4` | Bad field or value |
> | `-5` | The target forum is at its post cap |
> | `-6` | The move target is not a forum channel |

> [accordion] followForumPost (opcode 756)
>
> | Code | Meaning |
> | - | - |
> | `-1` | Not authenticated |
> | `-2` | Follow denied (not a member, or no view permission on the forum) |
> | `-3` | No such post under that forum |

> [accordion] fetchForumMeta (opcode 757)
>
> | Code | Meaning |
> | - | - |
> | `-1` | Not authenticated |
> | `-2` | Not a member of that server, or no view permission on the forum |
> | `-3` | Not a forum channel, or a server error while reading its settings |

> [accordion] Updating forum settings (opcode 758, raw lane only)
>
> The SDK has no method for this. The table exists so a raw-frame deny still reads as itself.
>
> | Code | Meaning |
> | - | - |
> | `-1` | Not authenticated |
> | `-2` | Settings change denied (missing `message_manage`) |
> | `-3` | Not a forum channel |
> | `-4` | Bad field or value |
> | `-5` | This forum is at its tag cap |

`reactToStarter()` is fire-and-forget on the wire and a denial produces no frame, so it never rejects with one of these.

### Interaction responses

`Interaction.ack()`, `showModal()`, and `ephemeral()` reject with these when the server refuses the response. The one you are most likely to see is `-3`: the click was more than 15 minutes ago. See [Buttons and selects](https://docs.cloak.chat/guides/components.md).

> [accordion] Responding to an interaction (opcode 796)
>
> | Code | Meaning |
> | - | - |
> | `-1` | Not authenticated |
> | `-2` | Not a bot session, or the kind and ciphertext disagree (an ack carries no payload; a modal and an ephemeral carry one) |
> | `-3` | No such interaction (it expired, 15 minutes after the click) |
> | `-4` | This interaction was already answered |
> | `-5` | This interaction addresses another bot |
> | `-6` | The response payload is over the 16 KiB wire cap |
> | `-8` | Server error while recording the response |

> [accordion] Sending a click (opcode 794, never sent by the SDK)
>
> This is the clicker's opcode. A bot session is refused with `-2` before the frame is read, so the SDK never sends it. The table exists so a raw-frame author reading `[794, -2]` learns why.
>
> | Code | Meaning |
> | - | - |
> | `-1` | Not authenticated |
> | `-2` | Bad frame, or sent from a bot session (bots never click) |
> | `-3` | No view permission on that channel (or not a participant of that DM) |
> | `-4` | The addressed bot is not a member of that server (or DM) |
> | `-5` | Rate limited (5 clicks per user per message per 10 seconds) |
> | `-6` | The interaction payload is over the 16 KiB wire cap |
> | `-8` | Server error while recording the interaction |

A second response to the same interaction never reaches the server. It is refused locally with a [`CloakClientError`](#cloakclienterror) whose `source` is `'interaction'`.

## Denied sends

`send()` has no success acknowledgement on the wire, so its promise resolves once the frame is out. A server-side denial arrives afterwards, on the [`sendRejected`](https://docs.cloak.chat/api-reference/events#sendrejected) event.

```ts theme={null}
client.on('sendRejected', (r) => {
  console.warn(`send denied (${r.code}): ${r.message}`);
  if (r.permission) console.warn(`missing ${r.permission}`);
});
```

The payload is `{ code, message, permission?, serverId, channelId, attribution, frame }`, with the same `message` and `permission` semantics as `CloakActionError`.

> [!WARNING]
>
> The deny frame carries no routing, so `serverId` and `channelId` come from the SDK's queue of sends still awaiting their echo, and `attribution` (`'exact'`, `'ambiguous'`, or `'none'`) says how much to trust them.
>
> `sendRejected` is not an acknowledgement channel. Silence does not mean delivered. A send made with `ack: true` gets a promise result instead: the persisted `Message`, a `CloakActionError` for a denial pinned to it, or a `CloakSendTimeoutError` below.

`sendRejected` does not also fire `error`. A backend denial is an expected outcome, not a plumbing failure.

## CloakClientError

Something failed inside the SDK's own plumbing: one of your handlers threw, a key pull died, or an inbound frame could not be dispatched. It surfaces on the [`error`](https://docs.cloak.chat/api-reference/events#error) event rather than as a rejection, because there is no call for it to reject. The one exception is `source: 'interaction'`, which is a rejected promise: the second of two responses to the same interaction.

```ts theme={null}
class CloakClientError extends Error {
  readonly source: CloakErrorSource;
  readonly context?: string;
  // plus `cause`, the original failure
}
```

**source** `CloakErrorSource`

Where it came from: `'listener'`, `'frame'`, `'keys'`, `'transport'`, `'reconnect'`, or `'interaction'`.

**context** `string | undefined`

The event name whose listener threw when `source` is `'listener'`. Otherwise a label for the failing call site.

**cause** `unknown`

The original failure, never swallowed and never wrapped twice.

| `source` | What failed |
| - | - |
| `listener` | One of your handlers threw, or returned a promise that rejected. `context` is the event name. |
| `frame` | An inbound frame could not be dispatched. |
| `keys` | A key pull, a key fetch, or an unwrap failed. |
| `transport` | The wire itself. |
| `reconnect` | The reconnect path. |
| `interaction` | An inbound click could not be decrypted or parsed (on the `error` event), or a second `ack()`, `showModal()`, or `ephemeral()` was called on one interaction (a rejected promise, with nothing sent). |

```ts theme={null}
client.on('error', (e) => {
  console.error(e.source, e.context, e.message);
  console.error(e.cause);
});
```

Registering the listener changes no control flow. It only makes failures visible. With no `error` listener, the behavior is what it was before the event existed: silent, plus a warning under `debug`.

## CloakEnvironmentError

The host is wrong, not your bot. An unsupported Node runtime, an optional native module the image cannot load, two packages that must move in lockstep and did not, an executable the audio path expected on `PATH`.

```ts theme={null}
class CloakEnvironmentError extends Error {
  readonly remedy: string;
  // plus `cause`
}
```

**remedy** `string`

One actionable paragraph naming what to change on the machine. Nothing about your bot's code, token, or permissions is at fault, so print this next to `message`.

```ts theme={null}
import { CloakEnvironmentError, generateDependencyReport } from '@cloak-software/bot-sdk';

try {
  await client.login();
} catch (e) {
  if (e instanceof CloakEnvironmentError) {
    console.error(e.message);
    console.error(e.remedy);
    console.error(generateDependencyReport());
  }
  throw e;
}
```

`login()` raises one on the first connect for a failure it recognizes, including an unsupported Node version. Reconnects keep their normal backoff and log the remedy under `debug`. The voice audio path raises the same class from `player.play()` and `ytdlpResource()`. See [Troubleshooting](https://docs.cloak.chat/production/troubleshooting.md).

## CloakSendTimeoutError

A send made with `ack: true` got neither its echo nor a deny inside `ackTimeoutMs`, the socket dropped while it waited, or the only deny that arrived could have belonged to another outstanding send. The outcome is **indeterminate**: the server may have persisted the message, or it may not, and nothing on the wire says which.

```ts theme={null}
class CloakSendTimeoutError extends Error {
  readonly indeterminate: true;
  readonly serverId: string | null;
  readonly channelId: string;
}
```

This is not a failure verdict. A retry can duplicate the message; not retrying can lose it. Read history when you must know. Distinct from `CloakActionError`, which is a definite denial pinned to exactly that send. See [Sending is fire-and-forget unless you ask for a receipt](https://docs.cloak.chat/concepts/message-delivery.md#sending-is-fire-and-forget-unless-you-ask-for-a-receipt).

## CloakRestError

An HTTP leg of the [REST lane](https://docs.cloak.chat/api-reference/rest.md) failed: cloak-rest-api answered non-2xx, or the request never left the host.

```ts theme={null}
class CloakRestError extends Error {
  readonly status: number;
  readonly path: string;
  readonly errorCode?: string;
}
```

**status** `number`

The HTTP status, or `0` for a transport failure such as DNS, TLS, or a timeout.

**path** `string`

The request path with the query string stripped, because ids ride query strings.

**errorCode** `string | undefined`

The service's machine-readable error code when the body carried one, for example `file_too_large`. Surfaced verbatim: the SDK hardcodes no server-side limit.

No credential material is ever quoted into this error, in `message`, in a field, or in `toString()`.

> [!NOTE]
>
> The credential **mint** is not an HTTP failure and rejects with `CloakActionError` instead. The most likely first error anyone sees from `client.rest` is code `-7`: bot REST credentials are disabled server-side, which is the shipping default. Nothing is wrong with your bot. An operator has to enable the feature.

## CloakEmbedError

A card [`sendCard()`](https://docs.cloak.chat/api-reference/client#sendcard) refused, thrown locally before anything reaches the wire. This class exists because the server cannot read an encrypted card and the renderer strips bad values silently, so this is the only place you can be told.

```ts theme={null}
class CloakEmbedError extends Error {
  readonly reason: CloakEmbedErrorReason;
  readonly field?: string;
}
```

**reason** `CloakEmbedErrorReason`

One of `'shape'`, `'content'`, `'cap'`, `'media-host'`, `'empty'`, or `'wire-cap'`.

**field** `string | undefined`

The exact offending path, for example `'embed.image.url'`. Absent when the whole payload is at fault.

`'media-host'` is the one you are most likely to hit: card media must be Cloak-hosted, and there is deliberately no flag that widens it. See [Rich cards](https://docs.cloak.chat/guides/rich-cards.md).

## CloakComponentError

A component row, a modal definition, or an ephemeral reply's rows were refused, thrown locally before anything reaches the wire. Raised by `sendCard()`, `editCard()`, `createForumPost()`, `Interaction.ephemeral()`, and `Interaction.showModal()`, and by `assertComponents()` and `assertModal()` when you call them yourself.

```ts theme={null}
class CloakComponentError extends Error {
  readonly reason: CloakComponentErrorReason;
  readonly field?: string;
}
```

**reason** `CloakComponentErrorReason`

`'shape'` for a wrong type, an unknown key, a missing required key, or a duplicate id. `'cap'` for a value over one of the pinned caps.

**field** `string | undefined`

The offending path, for example `'components[1].components[0].label'`.

Every cap is listed under [Component constants](https://docs.cloak.chat/api-reference/embeds.md#component-constants). The client parser enforces the same caps and drops a card whole on a violation, which is why the SDK refuses it first. See [Buttons and selects](https://docs.cloak.chat/guides/components.md).

## CloakWebhookError

A webhook POST failed, from either [`webhooks.post()`](https://docs.cloak.chat/api-reference/webhooks) or [`sendEmbed()`](https://docs.cloak.chat/api-reference/client#sendembed).

```ts theme={null}
class CloakWebhookError extends Error {
  readonly status: number;
  readonly detail: string;
  readonly webhookId?: string;
}
```

**status** `number`

The HTTP status, or `0` for a transport failure or a local precheck.

**detail** `string`

The ingress' own label, such as `'unauthorized'`, `'rate limited'`, or `'embeds too large'`. When `status` is `0`, an SDK-side label such as `'transport'` or `'precheck'`.

**webhookId** `string | undefined`

The webhook this post targeted, when known. Never the secret.

The webhook url never appears in the error, because it embeds the token secret.

## Login failures

Login rejections do not throw from a call you can await once the reconnect loop owns the connection. They emit [`disconnect`](https://docs.cloak.chat/api-reference/events#disconnect).

Two are **terminal** and stop the loop, because retrying cannot fix either:

| Code | Meaning | What to do |
| - | - | - |
| `-2` | The bot token was revoked or regenerated. | Issue a new token in **Settings > My Bots** and redeploy. |
| `-12` | This SDK is below the backend's minimum wire version. | Upgrade `@cloak-software/bot-sdk` and redeploy. |

`-8` is a transient backend error and keeps retrying with backoff. If your bot goes quiet and no `reconnecting` follows a `disconnect`, you are looking at `-2` or `-12`. See [Connection lifecycle](https://docs.cloak.chat/concepts/connection-lifecycle.md).

## describeActionError

```ts theme={null}
describeActionError(opcode: number, code: number): { message: string; permission?: PermissionName }
```

An exported helper that maps a raw `(opcode, code)` pair to the same message and optional permission that `CloakActionError` uses. Unknown codes get a generic message. You rarely need it, since a thrown error already carries both. It is there for tooling that inspects raw failures.

## Next

> [card] [Handling errors](https://docs.cloak.chat/guides/handling-errors.md)
>
> The catch-and-report pattern in practice.

> [card] [Permissions](https://docs.cloak.chat/api-reference/permissions.md)
>
> What the permission field points at.

> [card] [Events](https://docs.cloak.chat/api-reference/events.md)
>
> The error and sendRejected events.

> [card] [Troubleshooting](https://docs.cloak.chat/production/troubleshooting.md)
>
> Environment failures and their remedies.


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