nodejs 捕获 promise 未处理的 reject

博客探讨了Node.js中未捕获Promise reject的情况,通常会导致静默错误。通过复现问题和引用官方文档,介绍了从6.6版开始,Node.js将发出警告来处理这种情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

正常情况下,对于没有捕获的 promise的reject 会直接静默的吃掉.而这不是我们想要的.
复现一下看看
function cb(){
    console.log('444');
    fdsaf.fdafdas = 777;
}

new Promise((resolve,reject)=>{
    cb(1)
})

解决:

文档

https://nodejs.org/dist/latest-v4.x/docs/api/process.html#process_event_unhandledrejection

process.on('unhandledRejection', (reason, p) => {
    console.log("Unhandled Rejection at: Promise ", p, " reason: ", reason);
    // application specific logging, throwing an error, or other logic here
});

toy code

process.on('unhandledRejection', (reason, p) => {
    console.log("Unhandled Rejection at: Promise ", p, " reason: ", reason);
    // application specific logging, throwing an error, or other logic here
});
function cb(){
    console.log('444');
    fdsaf.fdafdas = 777;
}

new Promise((resolve,reject)=>{
    cb(1)
})

toy code2 co

process.on('unhandledRejection', (reason, p) => {
    console.log("Unhandled Rejection at: Promise ", p, " reason: ", reason.stack);
    // application specific logging, throwing an error, or other logic here
});
var co = require('co');

function cb(){
    console.log('444');
    fdsaf.fdafdas = 777;
}

co(function*(){
    console.log('1111');
    throw 'myerror```';
}).then(function(value) {
    console.log(value); // Success!
}).catch(err=>{
    console.log('222');
    console.log(err); // Error!
    cb();
    console.log('!!!!');
}).catch(err=>{
    console.log('aaa :',err);
})

nodejs 6.6以后.对没有捕获的 reject 会发出一个警告.

promises: Unhandled rejections now emit a process warning after the first tick. (Benjamin Gruenbaum) #8223

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值