实现说明
底层就是函数 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);