有没有童鞋遇到过同样的问题:Promise捕获未处理的异常?万分感谢

console.log('herewego');newPromise(resolve=>{setTimeout(()=>{console.log(2)thrownewError('bye');//这里不行},2000);//thrownewError('bye');//放这里可以}).then(value=>{console.log(value+'world');}).catch(error=>{console.log('Error:',error.message);});
鸿蒙传说
浏览 518回答 2
2回答

湖上湖

首先,在非async函数中,try-catch并不能捕获异步操作中产生的异常,Promise/setTimeout都是典型的异步操作。其次,Promise的catch会在resolve被调用之前throw的Error对象,或者reject被调用后触发。最后,setTimeout是个异步操作,当前操作执行完之后才会执行,所以当前的try-catch并不能处理setTimeout回调的异常。综合以上3点,你的throw在setTimeout中,且没有reject,Promise不能catch到如果移动到setTimeout下一句,相当于你的Promise没有resolve之前throw了Error

繁星淼淼

Node.js中未处理的Promise错误监听unhandledRejection事件,即可捕获到未处理的Promise错误:1process.on('unhandledRejection', (reason, promise) => ···);示例代码:1234567891011process.on('unhandledRejection', reason =>{    console.log(reason); // 打印"Hello, Fundebug!"}); function foo(){    Promise.reject('Hello, Fundebug!');} foo();注: Node.js v6.6.0+ 默认会报告未处理的Promise错误,因此不去监听unhandledrejection事件也没问题。Fundebug的Node.js错误监控插件监听了unhandledRejection事件,因此可以自动捕获未处理Promise错误。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript