-
-
Notifications
You must be signed in to change notification settings - Fork 117
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
unhandledrejection 处理没有显式捕获的 Promise 异常 #7
Comments
如果使用es7的async来写代码 await asyncFunc()
func1()
func2() 此时 |
@erguotou520 跟Promise的方式一样 try catch都能捕获es7的await返回的reject |
try catch 写起来反而没promise方式好看,而且有的业务逻辑不适合使用全局onerror处理 |
当 Promise 发生异常后,会从 相关阅读 |
@erguotou520 而且unhandledrejection/onerror应该统一用来处理那些漏掉的异常吧, |
@taixw2 我们说的场景不一样,我指的是确实需要处理的异常,属于正常的异常。 |
看了你们的讨论,感觉
其实个人感觉全局捕获异常不让输出到控制台可能显得干净,但是也不利于开发定位错误;还要一个不好的地方就是,如果要细粒度地针对情况处理每一种异常,就可能导致事件的回调变的很臃肿,执行时间更长。 我觉得最好是在每个Promise后都手动加上 |
chrome :69 两个事件均无触发 window.addEventListener('unhandledrejection', event =>
{
console.log(event.reason); // 打印"Hello, Fundebug!"
});
window.addEventListener('rejectionhandled', event =>
{
console.log('rejection handled'); // 1秒后打印"rejection handled"
});
function foo()
{
return Promise.reject('Hello, Fundebug!');
}
var r = foo();
setTimeout(() =>
{
r.catch(e =>{});
}, 1000); |
请问找到原因了吗,困惑,是chrome的问题吗? |
请问找到原因了吗? 我在vue和angular里作了这个例子打包后运行,angular能正常捕获,vue不能,怀疑是babel版本造成的,但没能找到解决方法。
|
看一下core-js的版本,unhandledrejection 只对原生的promise有效,如果是polyfill,看一下polyfill中的promise 该如何捕获 |
直接在console里执行或者协议是file:///都不会触发,你运行在http localhost下会有输出。 |
我也遇到了这个问题,发现问题在于引入的js资源于当前网址不同源导致的,unhandledrejection跟随同源策略 |
我们经常会写如下代码:
上面的代码有一处问题,就是异步
asyncFunc()
函数可能会 reject,这时我们并没有捕获 Promise 的 reject 分支。我们可以使用
window.addEventListener('unhandledrejection', event => ···);
来处理所有 Promise 的异常情况。根据 MDN 的兼容性表格看,好像目前只有 Chrome 支持这个事件。在 can i use 网站也搜不到关于
unhandledrejection
的相关信息。除了这个事件之外,还有一个
rejectionhandled
事件:表示 rejection 当时并没有立即处理,在之后的一段时间内处理了,此时触发rejectionhandled
事件。关于 Promise 的 Rejection 处理,Google 的 Chrome 团队有个演示页面:Promise Rejection Events Sample
即使异常被处理了,DevTools 依然会有错误信息:
如果需要禁用此错误信息,需要在
unhandledrejection
事件处理函数中调用:相关链接
The text was updated successfully, but these errors were encountered: