比如一个函数调用时缺少了一个必需的参数,这种情况应该尽早的返回异常,而不是在 Promise 中处理:
function foo(name) {
if (!name) {
return Promise.reject(new Error('name is required!'))
}
return new Promise((resolve, reject) => {/* ... */})
}
Promise 只能捕获在 .then
中产生的异常,所以不应该在 Promise 外 throw new Error
。
处理未捕获的异常:
function foo() {
fetch('xxx.json')
.then()
.then()
}
像这个函数就是无法捕获 Promise 中产生的异常的,它会 fail silently
。
然而你可以监听相关事件来处理:
// browser
window.addEventListener('unhandledrejection', event => {
// Prevent error output on the console:
event.preventDefault()
console.log('Reason: ' + event.reason)
})
window.addEventListener('rejectionhandled', event => {
console.log('REJECTIONHANDLED')
})
// node.js
process.on('unhandledRejection', reason => {
console.log('Reason: ' + reason)
})
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too