解决 Node.js 报错 UnhandledPromiseRejection: unhandled rejection 异步捕获修复
排查 Node.js 异步代码未捕获异常导致 UnhandledPromiseRejection 警告或退出,规范 async/await try-catch 与全局监听器。
问题现象
在 Node.js 应用运行中,异步 Promise 发生错误后未被捕获,终端打印警告并在 Node 15+ 中导致进程直接崩溃退出:
node:internal/process/promises:288
triggerUncaughtException(err, true /* fromPromise */);
^
[UnhandledPromiseRejection: 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().] {
code: 'ERR_UNHANDLED_REJECTION'
}
微服务 Pod 突发退出,触发容器重启。
触发根因
在 ECMAScript 异步模型中:
- 未消费的 Reject 状态:当一个 Promise 状态变更为
rejected,但在当前微任务队列(Microtask Queue)结束前,没有任何.catch()方法注册或包裹在try/catch块中; - Node.js 严格模式崩溃规范:早期 Node.js 仅打印
UnhandledPromiseRejectionWarning,从 Node.js 15 开始默认将未处理的 Rejection 提升为未捕获异常(Exit Code 1),直接导致主事件循环崩溃; - 事件监听器或定时器内部的异步裸调用:例如
setTimeout(async () => { throw new Error(...) }, 100),外部的调用栈无法捕获异步微任务中的抛出。
解决步骤
1. 为所有 async 函数调用链添加规范的 try/catch
在 async/await 语法下,严禁裸跑无保护的外部调用:
async function handleUserRequest(req, res) {
try {
const data = await fetchUserData(req.params.id);
res.json(data);
} catch (error) {
console.error('Failed to fetch user:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
}
2. 避免在 Express 路由中遗漏异步错误传递
在 Express 4.x 中,异步错误不会自动流转至错误处理中间件,使用包装器或 Express 5:
// Express 4 异步包装器
const asyncHandler = fn => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
app.get('/users', asyncHandler(async (req, res) => {
const users = await db.getUsers();
res.json(users);
}));
3. 注册全局 unhandledRejection 兜底监听器
在应用启动入口添加全局防御(记录致命日志并安全优雅停机):
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
// 在生产中记录致命日志并在完成剩余请求后优雅退出
process.exit(1);
});
验证确认
在测试脚本中模拟异步异常:
Promise.reject(new Error("Test Rejection")).catch(err => console.log("Safely caught:", err.message));
所有错误均通过标准链路被安全消费与处理,进程稳定持续运行,未再发生 UnhandledPromiseRejection 闪退。


