错误处理
本文介绍 SDK 的 TResult 错误处理模式,包括类型结构、使用方式、错误码设计和最佳实践。
TResult 设计理念
SDK 的所有异步公开方法均返回 TResult<T> 类型:
- 可预期的错误通过
result.ok === false表达 - 本地化消息通过
result.message直接展示给用户 - 排障信息通过
result.detail提供给开发者 - 错误码通过
result.code支持程序化处理
TResult<T> 类型结构
typescript
// 成功结果
interface TResultOk<T> {
ok: true;
data: T; // 成功时的返回数据
code: 0;
message: '';
detail: '';
}
// 失败结果
interface TResultFail {
ok: false;
data: undefined;
code: TResultCode; // 错误码枚举
message: string; // 本地化消息(可直接展示给用户)
detail: string; // 英文排障信息(供开发者定位问题)
}
// 联合类型
type TResult<T = void> = TResultOk<T> | TResultFail;基本使用
typescript
// 标准用法:检查 ok 后取数据
const result = await classroom.joinClass(params);
if (!result.ok) {
// 失败分支
showToast(result.message); // 展示给用户
console.error(result.detail); // 开发调试
console.error('错误码:', result.code); // 程序化处理
return;
}
// 成功分支 — TypeScript 自动收窄类型,result.data 可安全访问
console.log('进房成功');带返回数据的方法
typescript
const result = await classroom.getCameraList();
if (result.ok) {
// result.data 类型为 TDeviceInfo[]
const cameras = result.data;
cameras.forEach(cam => console.log(cam.deviceId, cam.label));
}TResultCode 错误码分段设计
错误码按模块分段,方便快速定位问题来源:
| 分段范围 | 模块 | 说明 |
|---|---|---|
1000 ~ 1999 | 框架 | 初始化、模块注册、生命周期 |
10000 ~ 10999 | API | 网络请求、服务端返回错误 |
20000 ~ 20999 | RTC | 音视频相关(设备、推流、拉流) |
30000 ~ 30999 | IM | 即时通讯相关(连接、发送、接收) |
40000 ~ 40999 | Board | 白板相关(初始化、渲染、同步) |
常用错误码
typescript
import { TResultCode } from '@tencent-classroom/sdk';
// 判断特定错误类型
const result = await classroom.startCamera(element);
if (!result.ok) {
switch (result.code) {
case TResultCode.NOT_INITIALIZED:
console.error('SDK 尚未初始化');
break;
case TResultCode.DEVICE_NOT_FOUND:
console.error('摄像头设备未找到');
break;
case TResultCode.PERMISSION_DENIED:
console.error('未授予摄像头权限');
break;
default:
console.error('未知错误:', result.message);
}
}统一错误通道
SDK 提供了统一错误事件,所有模块的运行时错误都会汇聚于此:
typescript
import { TEvent } from '@tencent-classroom/sdk';
classroom.on(TEvent.ERROR, ({ module, code, message, detail }) => {
console.error(`[${module}] ${code}: ${message}`);
// 上报错误日志
reportError({ module, code, message, detail });
});
classroom.on(TEvent.WARN, ({ module, message }) => {
console.warn(`[${module}] ${message}`);
});