运行WhatsApp Bot时出现未处理Promise拒绝问题求助
WhatsApp Bot 未处理Promise拒绝错误修复
问题描述
运行WhatsApp Bot时,接收消息触发以下错误:
at /root/bot/node_modules/@adiwajshing/baileys/lib/Utils/generics.js:157:32 (node:26706) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 21)
涉及的超时处理代码:
// Create a promise that rejects in <ms> milliseconds const { delay, cancel } = (0, exports.delayCancellable)(ms); const p = new Promise((resolve, reject) => { delay .then(() => reject(new boom_1.Boom('Timed Out', { statusCode: Types_1.DisconnectReason.timedOut, data: { stack } }))) .catch(err => reject(err)); promise(resolve, reject); }) .finally(cancel); return p; }
错误定位在generics.js:157的then(() => reject(new boom_1.Boom('Timed Out', {行。
修复方案
1. 给顶层Promise添加错误捕获
所有调用这段超时逻辑的地方,必须添加.catch()处理,或用try/catch包裹异步调用:
// 链式调用方式 timeoutPromise(5000, someAsyncTask) .then(result => { // 处理任务结果 }) .catch(err => { console.error('操作失败:', err); // 可添加错误通知、日志记录等逻辑 }); // async/await方式 async function executeTask() { try { const result = await timeoutPromise(5000, someAsyncTask); // 处理任务结果 } catch (err) { console.error('操作失败:', err); } }
2. 优化超时逻辑内部实现
原代码手动创建Promise的方式容易出现重复reject问题,改用Promise.race简化逻辑,同时确保错误链路清晰:
// 修改后的超时处理函数 const { delay, cancel } = (0, exports.delayCancellable)(ms); const p = Promise.race([ // 执行目标异步任务 new Promise(promise), // 超时逻辑 delay.then(() => { throw new boom_1.Boom('Timed Out', { statusCode: Types_1.DisconnectReason.timedOut, data: { stack } }); }) ]) .catch(err => { // 统一捕获错误,确保不会遗漏 throw err; // 继续抛出给上层处理 }) .finally(cancel); return p;
3. 全局捕获未处理Promise拒绝(临时应急)
如果暂时无法定位具体未捕获点,可添加全局监听避免进程崩溃:
process.on('unhandledRejection', (reason, promise) => { console.error('未处理的Promise拒绝:', reason); // 可添加日志上报等应急处理 });
注意:这只是临时方案,最终必须找到具体未捕获的Promise并添加针对性处理。
额外建议
- 检查并升级baileys库到最新稳定版,官方可能已修复此类超时处理的潜在问题
- 梳理所有异步操作(消息接收、API调用等),确保每个Promise都有对应的错误捕获逻辑
内容的提问来源于stack exchange,提问作者Gabriel Dimas Eka Jaya
相关产品推荐
相关产品推荐

