DEBUG.WIKI
阿里云;从建站到云上业务;云服务器 · 数据库 · 对象存储;查看产品 →
PanstarCloud:部署应用,接入 AI,云服务器与 AI 网关
IPPeak:从目标地区访问网页,住宅代理、SEO 监测、广告验证

解决 Node.js 报错 UnhandledPromiseRejectionWarning 的排查指南

排查与解决 Node.js 异步 Promise 被 reject 但未被 catch 捕获导致抛出告警与进程崩溃的完整方案。

问题现象

在运行 Node.js 服务或处理异步任务时,控制台输出黄色警告或在 Node.js 16+ 中直接引发致命崩溃(Exit code 1):

(node:1234) UnhandledPromiseRejectionWarning: Error: Database connection failed
    at connectDB (/app/db.js:15:11)
(node:1234) 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().
(node:1234) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

触发根因

  1. 异步函数内部通过 throw new Error() 或 Promise.reject() 拒绝了 Promise。
  2. 调用该异步操作的代码处既没有使用 .catch(err => ...),也没有在 await 外部包裹 try { ... } catch (err) { ... } 代码块。
  3. 在 Express/Koa 等 Web 框架的路由处理函数中,未将异步异常正确传递给全局错误中间件。

解决步骤与操作命令

步骤一:为 async/await 补充完善的 try/catch 保护

在异步业务流程中捕获并处理异常:

async function handleUserRequest(req, res) {
    try {
        const data = await fetchUserData(req.params.id);
        res.json({ success: true, data });
    } catch (err) {
        console.error("Failed to fetch user:", err.message);
        res.status(500).json({ success: false, error: "Internal Server Error" });
    }
}

步骤二:对纯 Promise 链条追加 .catch()

sendNotification(userId, message)
    .then(result => logSuccess(result))
    .catch(error => {
        // 捕获并记录,防止未处理拒绝抛出到运行时
        logError("Notification failed:", error);
    });

步骤三:在进程入口配置全局兜底兜底事件

在服务入口文件(如 index.js)监听 unhandledRejection 事件记录日志并优雅关闭:

process.on('unhandledRejection', (reason, promise) => {
    console.error('Unhandled Rejection at:', promise, 'reason:', reason);
    // 视业务严重程度决定是否退出进程
    // process.exit(1);
});

验证确认

模拟网络异常触发下游服务拒绝对接: 系统优雅记录错误日志并向调用端返回友好的错误响应,进程持续健康运行,未再输出 UnhandledPromiseRejectionWarning。