unhandledRejection Surfaces Missed Rejections
Promises rejected without a handler never throw a stack trace: attach process.on("unhandledRejection") to record the reason and keep the process alive.
Code
// 没有 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);Output
Captured from a sandboxed run of this snippet in the build pipeline.
recorded: metrics endpoint offline
process alive after the missed rejectionInside the snippet
unhandledRejection Surfaces Missed Rejections keeps everything in the function sendMetrics.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Using it
The primary signature is function sendMetrics()
Output lines are prefixed (recorded:, process alive after the missed rejection), making each step’s effect easy to spot.
Key statements
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);
Interactive Tools for This Topic
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. The file defines `sendMetrics` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.