> For the complete documentation index, see [llms.txt](https://dnotifier.gitbook.io/product-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dnotifier.gitbook.io/product-docs/realtime-communication/error-handling.md).

# Error handling & reconnection

DNotifier SDKs surface connection failures, send errors, and disconnect events through **thrown exceptions** and **`onDisconnected` callbacks**. The SDK does **not** auto-reconnect — your app owns retry policy and offline UX.

***

## Common error sources

| Phase                     | Error            | Typical cause                                        |
| ------------------------- | ---------------- | ---------------------------------------------------- |
| `connect()`               | Thrown exception | Wrong `secret`, invalid `appId`, plan issue, network |
| `send()` / `sendBinary()` | `Not connected`  | Called before `connect()` or after disconnect        |
| `send()`                  | Validation error | Missing `senderId`, `receiverId`, or `receiverIds`   |
| Transport                 | `onDisconnected` | Network loss, server close, explicit `disconnect()`  |

***

## Handle disconnects

Register `onDisconnected` at construction:

```js
const notifier = new DNotifier({
  // ...
  onDisconnected: ({ code, reason }) => {
    console.log("Disconnected:", code, reason);
    showOfflineBanner();
    scheduleReconnect();
  },
});
```

Dart:

```dart
onDisconnected: ({code, reason}) {
  print('Disconnected: $code $reason');
  showOfflineBanner();
  scheduleReconnect();
},
```

***

## Reconnection pattern

{% hint style="warning" %}
Always create a fresh `connect()` after disconnect. Do not call `send()` while `isConnected` is `false`.
{% endhint %}

```js
let reconnectTimer = null;

function scheduleReconnect() {
  if (reconnectTimer) return;
  reconnectTimer = setTimeout(async () => {
    reconnectTimer = null;
    try {
      await notifier.connect();
      hideOfflineBanner();
    } catch (err) {
      console.error("Reconnect failed:", err.message);
      scheduleReconnect(); // exponential backoff recommended
    }
  }, 3000);
}
```

Dart equivalent:

```dart
Future<void> reconnectWithBackoff(DNotifier notifier) async {
  for (var attempt = 1; attempt <= 5; attempt++) {
    try {
      await notifier.connect();
      return;
    } catch (e) {
      await Future.delayed(Duration(seconds: attempt * 2));
    }
  }
}
```

***

## Send error handling

```js
try {
  await notifier.send({
    senderId: myUserId,
    receiverId: peerUserId,
    data: { type: "text", text: "Hello" },
  });
} catch (err) {
  if (err.message === "Not connected") {
    await notifier.connect();
    // retry once
  } else {
    showSendFailedToast(err.message);
  }
}
```

***

## Auth failures at connect

```js
try {
  await notifier.connect();
} catch (err) {
  if (err.message.includes("401") || err.message.includes("auth")) {
    promptReLogin(); // refresh credentials from your backend
  } else {
    showNetworkError();
  }
}
```

Never log `secret` or `authToken` in production error reports.

***

## Chunk reassembly failures

If the connection drops while a large message is chunking:

* Partial chunks are discarded on the receiver
* The sender should retry the full `send()` after reconnect
* Consider showing "Message failed to send" in chat UI with a retry button

→ [Large messages & chunking](/product-docs/realtime-communication/chunking.md)

***

## Explicit disconnect

```js
notifier.disconnect();
// isConnected === false; onDisconnected fires
```

Use when the user logs out or your app tears down the realtime session.

***

## Production checklist

1. **Listen to `onDisconnected`** — update UI and pause sends
2. **Exponential backoff** — avoid hammering auth on flaky networks
3. **Idempotent history load** — after reconnect, `fetchChatHistory` to fill gaps
4. **Deduplicate by `metadata.id`** — if your app retries sends

→ [Production checklist](/product-docs/operations/production-checklist.md)

***

## Related topics

* [Connection lifecycle](/product-docs/realtime-communication/connection-lifecycle.md)
* [Plan limits & quotas](/product-docs/realtime-communication/plan-limits.md)
* [Chat history](/product-docs/chat/chat-history.md) — recover missed messages after reconnect
