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

解决 Node.js 报错 UnhandledPromiseRejection 未捕获异步异常

分析 Node.js 在 Promise 失败时未添加 catch 处理导致进程警告或崩溃的根因,提供 try/catch 与全局监听方案。

问题现象

Node.js 应用在执行异步任务时在控制台输出警告(在 Node 15+ 中会直接导致进程崩溃闪退):

(node:1234) UnhandledPromiseRejectionWarning: Error: Database query timed out
    at Query.run (/app/db.js:45: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. 在 async 函数内部抛出了异常,调用方使用 await 时没有包裹在 try ... catch 块中。
  2. 直接调用了返回 Promise 的函数,但遗漏了 .catch() 错误处理器。

解决步骤与操作命令

步骤一:针对 async/await 补全 try/catch 保护

// 规范写法
async function handleUserRequest(req, res) {
    try {
        const user = await getUserFromDb(req.params.id);
        res.json(user);
    } catch (err) {
        console.error('Failed to get user:', err);
        res.status(500).json({ error: 'Internal Server Error' });
    }
}

步骤二:针对传统 Promise 链式调用添加 .catch()

fetchData()
    .then(data => processData(data))
    .catch(err => console.error('Fetch error:', err));

步骤三:添加全局未捕获 Promise 兜底监听器(防进程崩溃)

在主入口文件(如 server.js)顶部注册:

process.on('unhandledRejection', (reason, promise) => {
    console.error('Unhandled Rejection at:', promise, 'reason:', reason);
    // 记录错误日志,并按需进行优雅关停
});

验证确认

重新运行业务压力测试: 所有异步异常均被精准捕获并记录结构化日志,服务进程常驻平稳,未再出现 DeprecationWarning 与闪退。