> 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/convai-unity-sdk/troubleshooting/connection-and-api-issues.md).

# 连接与 API 问题

解读 Convai 会话错误代码、查看房间管理器诊断信息，并解决身份验证、传输和限流失败。

所有会话错误都通过 `ConvaiSessionEventRelay.OnSessionError` 事件上报。该事件负载包含一个 `ErrorCode` 字符串和一个人类可读的 `消息`。错误代码遵循层级式点号表示法： `{category}.{detail}`。类别前缀会告诉你系统的哪一层发生了故障。

| 类别前缀           | 发生了什么故障                                          |
| -------------- | ------------------------------------------------ |
| `config.*`     | SDK 配置——缺少 API 密钥、Character ID，或 Auth Token 模式设置 |
| `connection.*` | Convai API 或网络——身份验证、路由、限制                       |
| `transport.*`  | WebRTC / LiveKit 层——ICE、对等连接、信号                  |
| `server.*`     | Convai 自身的管道——配额、致命错误                            |
| `session.*`    | 会话生命周期——令牌过期、状态冲突                                |

### 订阅会话错误

添加 `ConvaiSessionEventRelay` 到与 `ConvaiManager` 相同的 GameObject 上，并在 Inspector 中连接，或者在代码中订阅：

```csharp
using Convai.Runtime.Presentation.Events;
using UnityEngine;

public class ErrorListener : MonoBehaviour
{
    [SerializeField] private ConvaiSessionEventRelay _sessionRelay;

    private void OnEnable()
    {
        _sessionRelay.OnSessionError.AddListener(OnError);
    }

    private void OnDisable()
    {
        _sessionRelay.OnSessionError.RemoveListener(OnError);
    }

    private void OnError(SessionErrorRelayData data)
    {
        Debug.LogError($"[MyApp] Session error: {data.ErrorCode} — {data.Message}");
    }
}
```

#### 直接读取错误状态

`ConvaiRoomManager` 将最新的错误代码和消息作为普通属性存储——无需事件订阅。这对于按需记录诊断状态非常有用：

```csharp
var room = FindFirstObjectByType<ConvaiRoomManager>();
Debug.Log($"State:           {room.CurrentState}");
Debug.Log($"Connected:       {room.IsConnected}");
Debug.Log($"Last error code: {room.LastSessionErrorCode}");
Debug.Log($"Last error msg:  {room.LastSessionErrorMessage}");
Debug.Log($"Connect attempts:{room.ConnectAttemptCount}  Reconnects: {room.ReconnectCount}");
```

### 配置错误

配置错误会在连接时立即触发——甚至在任何网络流量之前。请先修复这些问题。

| 错误代码                                 | 说明                                                                                 | 修复方法                                                                                                                                                                                             |
| ------------------------------------ | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `config.api_key_missing`             | API 密钥字段为空，位于 `ConvaiSettings`                                                     | 打开 Edit → Project Settings → Convai SDK 并粘贴你的 API 密钥                                                                                                                                             |
| `config.character_id_missing`        | `角色 ID` 字段在 `ConvaiCharacter` 为空                                                   | 在 `ConvaiCharacter` Inspector 字段中设置 Character ID                                                                                                                                                 |
| `config.auth_token_provider_missing` | Auth Mode 为 Auth Token，但没有 `IConvaiAuthTokenProvider` 被注册，且没有配置 Token Endpoint URL | 注册提供程序或配置 Token Endpoint URL——参见 [排查身份验证问题](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/authentication/troubleshooting.md)                                                                |
| `config.auth_token_endpoint_invalid` | 所配置的 Token Endpoint URL 不是 HTTPS，也不是本地回环开发地址                                       | 使用 `https://`，或 `http://localhost` / `http://127.0.0.1` 用于本地开发——参见 [排查身份验证问题](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/authentication/troubleshooting.md)                              |
| `config.auth_token_mode_required`    | `ConnectWithAuthTokenAsync` 在 Auth Mode 仍为 API Key 时被调用                            | 在调用前将 Convai Project Settings 中的 Auth Mode 设置为 Auth Token `ConnectWithAuthTokenAsync` 来驱动目标——参见 [排查身份验证问题](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/authentication/troubleshooting.md) |

{% hint style="warning" %}
如果 API 密钥为空，SDK 会在任何连接尝试之前发出警告： `Convai Bootstrapper: API key not configured. Please set your API key in Edit > Project Settings > Convai SDK.` 这会在 Play 时触发——在测试连接之前先修复它。
{% endhint %}

### 连接错误

当 Convai 拒绝连接请求或无法完成连接请求时，会出现这些代码。其中大多数都有明确原因和直接修复方法。

| 错误代码                                            | 说明                                         | 自动重试 | 修复方法                                                                                                               |
| ----------------------------------------------- | ------------------------------------------ | ---- | ------------------------------------------------------------------------------------------------------------------ |
| `connection.connect_invalid_api_key`            | API 密钥被 Convai 拒绝                          | 否    | 从 Convai 仪表板复制一个新的密钥；检查末尾是否有空格                                                                                     |
| `connection.auth_token_fetch_failed`            | Auth Token 模式在连接前未能解析出令牌（提供程序异常、令牌为空或端点失败） | 是    | 参见 [排查身份验证问题](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/authentication/troubleshooting.md) 以查看确切的控制台消息和原因 |
| `connection.auth_failed`                        | 身份验证失败（令牌已撤销或凭据无效）                         | 否    | 重新输入你的 API 密钥；检查该密钥是否已在仪表板中被撤销                                                                                     |
| `connection.invalid_token`                      | 提供的连接令牌无效                                  | 否    | 令牌是内部生成的——如果出现此项，请重新连接以生成新的令牌                                                                                      |
| `connection.connect_invalid_session_id`         | 连接请求使用了无效的会话标识符                            | 否    | 会话 ID 是内部生成的——请重新连接以重置会话                                                                                           |
| `connection.connect_character_not_found`        | 你的账户上不存在该 Character ID                     | 否    | 请确认 Convai 仪表板中的 Character ID 完全一致                                                                                 |
| `connection.connect_realtime_not_allowed`       | 该账户未启用实时访问                                 | 否    | 升级你的 Convai 套餐或联系支持                                                                                                |
| `connection.connect_concurrency_limit_reached`  | 你的套餐同时会话数量上限已达到                            | 是    | 断开空闲角色；升级套餐以获得更高上限                                                                                                 |
| `connection.connect_speaker_limit_reached`      | 该账户已达到后端说话者上限                              | 否    | 减少同时激活的角色数量，或提高你账户的上限。SDK 不会重试这一项——与并发限制不同，它被视为硬性限制，而不是瞬态条件。                                                       |
| `connection.connect_bot_start_failed`           | Convai 管道启动失败（后端临时问题）                      | 是    | SDK 会自动重试；如果持续发生，请联系支持                                                                                             |
| `connection.connect_unhandled_server_exception` | 连接期间 Convai 发生未处理异常                        | 是    | SDK 会自动重试；如果持续发生，请查看 Convai 状态页                                                                                    |
| `connection.timeout`                            | 连接未能在超时窗口内完成                               | 是    | 检查互联网连接；增加 **连接超时** 在设置中（默认 30 秒，最大 120 秒）                                                                         |
| `connection.network_error`                      | DNS 失败、套接字错误或网络不可达                         | 是    | 验证互联网连接；检查防火墙是否阻止了 Convai 域名                                                                                       |
| `connection.rate_limited`                       | 在很短时间内发起了过多连接请求                            | 是    | 降低重新连接尝试的频率；在代码中增加重试间隔                                                                                             |
| `connection.service_unavailable`                | Convai 临时不可用（HTTP 503）                     | 是    | 等待后重试；SDK 会自动退避                                                                                                    |
| `connection.server_error`                       | Convai 返回了 5xx 错误                          | 是    | 瞬态问题——SDK 会重试；如果持续发生，请查看 Convai 状态页                                                                                |
| `connection.not_found`                          | 未找到资源（角色或房间）（HTTP 404）                     | 否    | 验证 Character ID 是否存在于你的账户中                                                                                         |
| `connection.bad_request`                        | 连接请求中的参数无效                                 | 否    | 检查 CharacterId 和其他连接参数是否包含无效字符                                                                                     |
| `connection.connect_validation_error`           | 连接请求未通过 API 验证（HTTP 422）                   | 否    | 查看错误消息，确认是哪个字段未通过验证                                                                                                |
| `connection.failed`                             | 未被特定代码覆盖的一般连接失败                            | 取决于  | 检查 `LastSessionErrorMessage` 详情                                                                                    |

### 传输错误

传输错误发生在 WebRTC / LiveKit 层，即 Convai 已接受连接请求之后。它们几乎总是瞬态的，SDK 会自动重试。

| 错误代码                               | 说明                       | 要检查什么                                   |
| ---------------------------------- | ------------------------ | --------------------------------------- |
| `transport.ice_failed`             | WebRTC ICE 协商失败——无法到达对等端 | 验证网络允许 UDP 流量；企业防火墙通常会阻止 WebRTC         |
| `transport.peer_connection_failed` | 无法建立 WebRTC 对等连接         | 与 ICE 失败相同——检查 UDP 端口以及 STUN/TURN 的可访问性 |
| `transport.livekit_error`          | LiveKit SDK 报告了一个错误      | 通常是瞬态问题；检查互联网稳定性                        |
| `transport.signal_disconnected`    | LiveKit 信令服务器连接中断        | 通常会自动重新连接；持续失败表明网络不稳定                   |

{% hint style="info" %}
WebRTC 需要 UDP 端口可访问。在企业部署中，请与你的网络团队合作，将 Convai LiveKit 端点加入白名单。完整的域名和端口列表请参见 Network & API Requirements 页面。
{% endhint %}

### 服务器和使用量错误

| 错误代码                         | 说明                    | 修复方法                          |
| ---------------------------- | --------------------- | ----------------------------- |
| `server.usage_limit_reached` | 已超过每日或每月使用配额          | 在 Convai 仪表板中查看使用情况；升级你的套餐    |
| `server.fatal_error`         | 致命管道错误——会话被 Convai 终止 | 会话无法恢复；发起新的连接                 |
| `server.error`               | Convai 报告的非致命管道错误     | SDK 会重试；如果持续发生，请向 Convai 支持报告 |

### 会话和协议错误

| 错误代码                       | 说明                    | 修复方法                         |
| -------------------------- | --------------------- | ---------------------------- |
| `session.token_expired`    | 会话令牌已过期               | 重新连接以获取新的令牌                  |
| `session.invalid_state`    | 在无效状态下尝试了某个操作         | 检查你的 connect/disconnect 调用顺序 |
| `session.cancelled`        | 会话已被你的代码取消            | 如果你调用 `DisconnectAsync` 手动   |
| `protocol.message_invalid` | 从 Convai 收到了无效的协议消息   | 通常表示 SDK/后端版本不匹配；更新 SDK      |
| `protocol.parse_failed`    | SDK 无法解析来自 Convai 的消息 | 通常表示 SDK/后端版本不匹配；更新 SDK      |

### 重试行为

对于瞬态错误，SDK 使用指数退避策略。一次失败后，它会在再次尝试前等待：

| 尝试次数  | 本次尝试前的延迟 |
| ----- | -------- |
| 1（初始） | 无——立即    |
| 2     | 1 秒      |
| 3     | 2 秒      |
| 4（最终） | 4 秒      |

在四次尝试后，SDK 会放弃并触发 `OnSessionError` 以及最终错误代码。 **非瞬态错误——例如无效 API 密钥、未找到角色或未启用实时访问——不会重试。** SDK 会立即触发 `OnSessionError` 。

以下错误代码会触发自动重试：

* `connection.timeout`
* `connection.network_error`
* `connection.server_error`
* `connection.service_unavailable`
* `connection.rate_limited`
* `connection.connect_concurrency_limit_reached`
* `connection.connect_bot_start_failed`
* `connection.connect_unhandled_server_exception`
* `connection.auth_token_fetch_failed`
* `transport.ice_failed`
* `transport.signal_disconnected`
* `server.error`

### 运行时诊断

读取 `ConvaiRoomManager` 状态属性来缩小连接失败的范围。属性会实时更新——无需事件订阅。关于完整的属性参考、诊断快照 API 和代码示例，请参见 Debug Tools Reference。

{% content-ref url="/pages/41fb22d336940f24c4bfbf2655c6122580016b9b" %}
[调试工具参考](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/troubleshooting/debug-tools-reference.md)
{% endcontent-ref %}

### 快速参考：常见失败模式

| 症状                                        | 可能原因                    | 修复方法                                                                 | 验证                             |
| ----------------------------------------- | ----------------------- | -------------------------------------------------------------------- | ------------------------------ |
| `config.api_key_missing` 在每次连接时           | 从未输入 API 密钥             | Edit → Project Settings → Convai SDK → 粘贴密钥                          | 重新进入 Play Mode——错误不再触发         |
| `connection.connect_invalid_api_key`      | API 密钥错误或已撤销            | 从 Convai 仪表板复制一个新的密钥                                                 | 会话达到 `已连接` state               |
| `connection.connect_character_not_found`  | Character ID 拼写错误或账户错误  | 在 Convai 仪表板中验证；检查复制粘贴时的空白字符                                         | 会话达到 `已连接` state               |
| `connection.connect_realtime_not_allowed` | 账户未启用实时功能               | 升级套餐                                                                 | 会话达到 `已连接` state               |
| `connection.timeout` 每次                   | 防火墙阻止连接                 | 将 Convai 域名加入白名单；在不同网络上尝试                                            | 会话在超时窗口内连接成功                   |
| `transport.ice_failed` 反复                 | 严格的防火墙阻止 UDP            | 允许 UDP；向网络管理员申请 TURN 中继                                              | 会话连接成功；WebRTC 协商完成             |
| `server.usage_limit_reached`              | 配额已超出                   | 查看 Convai 仪表板的使用情况页面                                                 | 在使用量重置或套餐升级后会话连接成功             |
| 角色连接一次后再也无法重新连接                           | `ReconnectPolicy` 已达到上限 | SDK 在 3 次重新连接尝试后停止（默认 `MaxReconnectAttempts`）；调用 `ConnectAsync` 再次重试 | `ConnectAsync` 调用成功；角色连接       |
| `connection.rate_limited`                 | 短时间内连接次数过多              | 在应用逻辑中为连接调用添加最小延迟                                                    | `connection.rate_limited` 不再触发 |
| `CurrentState` 卡在 `错误`                    | 无法恢复的会话失败               | 调用 `DisconnectAsync()` 然后 `ConnectAsync()` 以重置                       | 会话转换为 `已连接`                    |

### 下一步

有关 SDK 日志系统、内置诊断工具和会话指标的完整参考，请参见 Debug Tools Reference。

{% content-ref url="/pages/41fb22d336940f24c4bfbf2655c6122580016b9b" %}
[调试工具参考](/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/troubleshooting/debug-tools-reference.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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.convai.com/api-docs/zh/cha-jian-yu-ji-cheng/convai-unity-sdk/troubleshooting/connection-and-api-issues.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
