如何修复Voximplant中的"NOT_LOGGED_IN"错误并恢复连接?
解决Voximplant后台切换后无法重连的问题
核心问题分析
从日志来看,应用进入后台时Voximplant连接已断开,但代码未监听ConnectionClosed事件,导致回到前台后无法自动触发重连;同时发起呼叫时未处理未登录状态的Promise拒绝,引发NOT_LOGGED_IN报错,最终只能通过重启应用恢复。
具体修复步骤
1. 监听ConnectionClosed事件,添加自动重连逻辑
在初始化Voximplant Client的代码中,注册ConnectionClosed事件监听,一旦触发就执行重新登录流程:
// 初始化Client时添加事件监听 const client = Voximplant.getInstance(); client.on(Voximplant.ClientEvents.ConnectionClosed, () => { reLoginToVoximplant(); }); // 实现重新登录函数 async function reLoginToVoximplant() { try { // 从本地缓存获取登录凭证(替换为你的实际缓存逻辑) const { username, password } = getStoredAuthInfo(); if (!username || !password) return; // 避免重复登录 if (client.getClientState() === Voximplant.ClientState.LOGGED_IN) return; await client.login(username, password); console.log("Voximplant重连登录成功"); } catch (error) { console.error("重连失败:", error); // 添加重试机制,间隔3秒后重试 setTimeout(reLoginToVoximplant, 3000); } }
2. 处理NOT_LOGGED_IN的Promise拒绝
在发起呼叫的代码中添加错误捕获,针对未登录状态触发重连:
async function initiateCall(number) { try { const client = Voximplant.getInstance(); // 发起呼叫前检查登录状态 if (client.getClientState() !== Voximplant.ClientState.LOGGED_IN) { await reLoginToVoximplant(); } // 执行呼叫逻辑 const call = await client.call(number); // 后续呼叫相关处理(如监听呼叫状态) } catch (error) { if (error === "NOT_LOGGED_IN") { console.error("当前未登录,触发重连"); await reLoginToVoximplant(); // 可选:重连后自动重试呼叫 // initiateCall(number); } else { console.error("呼叫失败:", error); } } }
3. 优化前后台切换的状态检查
在_handleAppStateChange方法中,针对active状态添加登录校验,确保回到前台时连接有效:
_handleAppStateChange = (state) => { console.log("Current app state changed to", state); const client = Voximplant.getInstance(); if (state === "active") { // 回到前台时检查登录状态,未登录则触发重连 if (client.getClientState() !== Voximplant.ClientState.LOGGED_IN) { reLoginToVoximplant(); } } }
关键注意事项
- 确保登录凭证已本地缓存,避免重连时需要用户重复输入
- 重连逻辑添加重试间隔,避免频繁请求触发服务端限制
- 所有异步操作(登录、呼叫)必须添加
try/catch,杜绝未处理的Promise拒绝
内容的提问来源于stack exchange,提问作者Ksenia Cherkasova
相关产品推荐
相关产品推荐

