← 中文资源

简体中文版本

unhandledRejection 兜住漏掉的 rejection

没有 handler 的 rejection 不会抛栈:挂上 process.on("unhandledRejection") 记录原因,进程继续存活,失败不再静默丢失。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

recorded: metrics endpoint offline
process alive after the missed rejection

实现说明

底层就是函数 sendMetrics。 每个异步步骤都被 await,拒绝会在发起调用的那一行浮出。

使用要点

  • 每一步打印都带着自己的标签:recorded:、process alive after the missed rejection。

常见问题

有第三方依赖吗?

没有。依赖清单是空的,代码只用标准库。 文件在加载时定义 sendMetrics。

主签名形如 function sendMetrics()

核心语句

return Promise.reject(new Error('metrics endpoint offline'));
process.on('unhandledRejection', (reason) => {
  console.log('recorded:', reason instanceof Error ? reason.message : String(reason));
});
setTimeout(() => sendMetrics(), 0);

代码示例

// 没有 await/catch 的 rejection 不会抛栈,只触发 unhandledRejection 事件
process.on('unhandledRejection', (reason) => {
  console.log('recorded:', reason instanceof Error ? reason.message : String(reason));
});

function sendMetrics() {
  return Promise.reject(new Error('metrics endpoint offline'));
}

// 演示用:这里刻意不挂 catch。放进定时器让 rejection 发生在事件循环任务里
setTimeout(() => sendMetrics(), 0);

setTimeout(() => {
  console.log('process alive after the missed rejection');
}, 20);