gpt4 book ai didi

javascript - promise catch 中的错误不会触发全局错误处理程序

转载 作者:行者123 更新时间:2023-12-05 03:21:21 32 4
gpt4 key购买 nike

为什么在 promise reject/catch 方法中抛出的错误不会触发全局错误处理程序?如何创建包含这些的全局错误处理程序?在我的应用程序中,全局错误处理程序会记录错误。

function doPromise() {
return Promise.reject()
}

window.addEventListener('error', function (e) { console.log('Global handler ' + e.message) })

doPromise()
.then()
.catch(e => {
console.log('Promise catch')
throw new Error('Promise catch error') // Does not trigger global error handler
})

throw new Error('Core error') // To prove global error handler is working

最佳答案

这不是错误,而是Unhandled Rejection :

The unhandledrejection event is sent to the global scope of a script when a JavaScript Promise that has no rejection handler is rejected

代码的工作版本:

function doPromise() {
return Promise.reject()
}

window.addEventListener('error', function(e) {
console.log('Global handler ' + e.message)
})
window.addEventListener('unhandledrejection', event=>{
console.log('Unhandled rejection', event)
}
);

doPromise().then().catch(e=>{
console.log('Promise catch')
throw new Error('Promise catch error')
// Does not trigger global error handler
}
)

throw new Error('Core error')
// To prove global error handler is working

关于javascript - promise catch 中的错误不会触发全局错误处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73002252/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com