> For the complete documentation index, see [llms.txt](https://docs.convai.com/api-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/error-handling.md).

# 处理错误和断开连接

捕获连接失败，使用你自己的重连逻辑应对会话中断，并读取 Convai 为每条消息返回的确认。

处理 Convai Web SDK 会话可能遇到的故障：连接始终无法建立、会话中断，以及 Convai 拒绝消息。当你从原型转向需要自行恢复的应用时，请参考本页面。

### 故障出现的位置

| 故障                 | 出现位置                                              |
| ------------------ | ------------------------------------------------- |
| `connect()` 无法建立会话 | `connect()`  promise 被拒绝，且 `error` 事件触发时会携带相同的错误。 |
| 角色始终未发出就绪信号        | 系统会触发  `error`  事件（仅限 LiveKit 传输）。                |
| 会话有意或无意地结束         | 系统会触发  `disconnect`  事件，并附带原因代码。                  |
| Convai 接受或拒绝您发送的消息 | 当 `serverResponse` 事件触发时。                         |
| 角色选择不作回答           | 当 `llmNoResponse` 事件触发时。                          |
| 会话因不活动即将超时         | 当 `idleWarning` 事件触发。                             |

### 捕获连接失败

将 `connect()` 放入 `try`/`catch`中。SDK 会发出 `error` ，其值与重新抛出的值相同，因此请在同一处处理，避免重复报告。

```typescript
try {
  await client.connect();
} catch (err) {
  showError(err instanceof Error ? err.message : String(err));
}
```

`connect()` 会在发送任何请求之前抛出以下错误：

| 消息                                                                              | 原因                   |
| ------------------------------------------------------------------------------- | -------------------- |
| `No configuration provided. Pass config to connect() or store it in the client` | 未向构造函数或 `connect()`. |
| `Either apiKey or authToken is required, and characterId is required`           | 缺少凭据或角色 ID。          |

当 Convai 响应 `/connect` 并返回错误状态时，错误消息来自响应正文中的 `message`, `error`或 `detail` 字段。列出多个问题的验证错误会合并为一条消息，格式如下： `field: problem; field: problem`。如果响应正文不可读，则会返回 `HTTP <status>` ，后跟正文文本。

error `error` 事件载荷的类型为 `unknown`，因为它可能包含任何导致失败的内容。读取属性前，请先缩小类型范围：

```typescript
client.on('error', (err: unknown) => {
  console.error(err instanceof Error ? err.message : err);
});
```

对于 LiveKit 传输，SDK 会在连接后等待角色发出就绪信号。如果 45 秒内未收到信号， `error` 事件会触发，错误为 `bot-ready not received within 45000ms`。会话仍保持连接；断开连接后重新连接即可恢复。

### 处理断开连接

disconnect `disconnect` 事件会收到一个 `DisconnectReason` 代码。当传输层未提供原因时，SDK 会报告 `0`。在 WebSocket 传输上调用 `disconnect()` 会报告 `1`。最后一次断开原因也可通过 `client.state.disconnectReason`获取； `null` 表示当前处于连接状态。

`getDisconnectReasonMessage()` 可将代码转换为文本。它和 `DisconnectReasonEnum` 均从以下模块导出： `@convai/web-sdk/core`, `@convai/web-sdk/react`以及 `@convai/web-sdk/vanilla`.

| 代码  | `DisconnectReasonEnum` 键 | `getDisconnectReasonMessage()` 文本          |
| --- | ------------------------ | ------------------------------------------ |
| `0` | `UNKNOWN_REASON`         | `Network unavailable or unknown cause`     |
| `1` | `CLIENT_INITIATED`       | `User disconnected`                        |
| `2` | `DUPLICATE_IDENTITY`     | `Another client with same identity joined` |
| `3` | `SERVER_SHUTDOWN`        | `Server is shutting down`                  |
| `4` | `PARTICIPANT_REMOVED`    | `Removed by RemoveParticipant API`         |
| `5` | `ROOM_DELETED`           | `Room ended via DeleteRoom API`            |
| `6` | `STATE_MISMATCH`         | `State mismatch`                           |
| `7` | `JOIN_FAILURE`           | `Failed to join`                           |
| `8` | `MIGRATION`              | `Participant moved to different room`      |
| `9` | `SIGNAL_CLOSE`           | `Signal connection closed`                 |

任何其他代码都会返回 `Disconnected`，并且 `null` 返回 `Connected`.

### 采用退避策略重连

SDK 不会自行重连：它为 LiveKit 房间配置了拒绝所有重试的策略。请在 `disconnect` 处理程序中，在断开连接原因并非主动断开时发起重连。

`reconnect()` 会使用上一次配置（包括 Convai 返回的角色会话 ID）重新连接，从而恢复对话。如果 `No stored config available for reconnection` 在 `connect()` 未使用配置运行过时，则会抛出此错误。

```typescript
import { DisconnectReasonEnum, getDisconnectReasonMessage } from '@convai/web-sdk/core';

async function retryWithBackoff(fn: () => Promise<void>, attempts = 3, delayMs = 500) {
  for (let i = 1; i <= attempts; i++) {
    try {
      return await fn();
    } catch (err) {
      if (i === attempts) throw err;
      await new Promise((r) => setTimeout(r, delayMs * 2 ** (i - 1)));
    }
  }
}

const doNotRetry: number[] = [
  DisconnectReasonEnum.CLIENT_INITIATED,
  DisconnectReasonEnum.DUPLICATE_IDENTITY,
  DisconnectReasonEnum.JOIN_FAILURE,
];

client.on('disconnect', (reason: number) => {
  console.log(getDisconnectReasonMessage(reason));
  if (!doNotRetry.includes(reason)) {
    void retryWithBackoff(() => client.reconnect());
  }
});
```

{% hint style="warning" %}
`disconnect()` 也会触发 `disconnect` 且 `CLIENT_INITIATED`。排除该代码，否则每次主动断开连接都会触发重连。
{% endhint %}

### 检查消息是否已被接受

大多数发送方法会返回 `void` ，并且在传输层未就绪时不会执行任何操作，也不会抛出异常。这包括 `sendUserTextMessage()`, `sendTriggerMessage()`, `sendInterruptMessage()`, `updateContext()`, `updateDynamicInfo()`, `updateTemplateKeys()`, `updateSceneMetadata()`, `toggleTts()`, `toggleStt()`以及 `resetIdleTimer()`。仅在 `botReady` 触发后发送：

```typescript
function safeSend(text: string) {
  if (!client.state.isConnected || !client.isBotReady) return;
  client.sendUserTextMessage(text);
}
```

`sendActionResult()` 是个例外：如果会话尚未就绪或结果无效，它会抛出异常。请参阅 [处理角色动作](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/actions.md).

Convai 会通过 `serverResponse` 事件确认消息。 `event_type` 是你发送的消息类型， `status` 则为 `success`, `error`, `processing`或 `pending`, `message` 是描述，或者为 `null`，而 `extras` 则包含特定于事件的数据，或者为 `null`.

```typescript
import type { ServerResponse } from '@convai/web-sdk/core';

client.on('serverResponse', (res: ServerResponse) => {
  if (res.status === 'error') {
    console.error(`${res.event_type} failed: ${res.message}`);
  }
  if (res.event_type === 'context-update' && res.extras) {
    const { token_count, max_tokens, remaining_tokens } = res.extras;
    console.log(`Context tokens: ${token_count}/${max_tokens}, ${remaining_tokens} left`);
  }
});
```

### 处理无响应轮次和空闲会话

`llmNoResponse` 当角色有意不回应某轮对话时触发。触发时，请清除所有思考指示器。

`idleWarning` Convai 关闭不活跃会话前触发。其负载为 `{ remainingSeconds }`，类型为数字或 `null`。在最终用户执行操作时调用 `resetIdleTimer()` ，以保持会话开启。

```typescript
client.on('llmNoResponse', () => hideThinkingIndicator());

client.on('idleWarning', ({ remainingSeconds }: { remainingSeconds: number | null }) => {
  if (remainingSeconds !== null) {
    showBanner(`Session closes in ${remainingSeconds} seconds`);
  }
});

document.addEventListener('pointerdown', () => client.resetIdleTimer());
```

### 妥善处理媒体控件

麦克风、摄像头和屏幕共享方法均为异步方法；如果浏览器拒绝权限或设备不可用，这些方法会被拒绝。请捕获拒绝并显示提示：

```typescript
try {
  await client.audioControls.toggleAudio();
} catch (err) {
  showError('Microphone unavailable. Check the browser permission.');
}
```

### 后续步骤

{% content-ref url="/pages/8c6e3631e7e7da5b3c9acf5a0019d7737dc79e19" %}
[Web SDK 事件参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/event-reference.md)
{% endcontent-ref %}

{% content-ref url="/pages/f1fc7386520b3ebeeafa719a8d9efb554e1d7024" %}
[ConvaiClient 参考](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/vanilla-typescript/convaiclient-core-api.md)
{% endcontent-ref %}

{% content-ref url="/pages/534e8cdc1d57114dcd7601d4455823f77a9ad2ef" %}
[使用认证令牌连接](https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/auth-tokens.md)
{% endcontent-ref %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/web-plugins/convai-web-sdk/error-handling.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
