当前位置:   article > 正文

nodejs 捕获 promise 未处理的 reject_process.on('unhandledrejection',function(err,promi

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

new Promise((resolve,reject)=>{
    cb(1)
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

解决:

文档

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
});
  • 1
  • 2
  • 3
  • 4

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)
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

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);
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/331958
推荐阅读
相关标签
  

闽ICP备14008679号