【发布时间】:2020-08-23 00:42:24
【问题描述】:
如果我调用的同步第三方函数从它正在调用的异步函数中抛出错误,我如何捕获错误?
// some asynchronous function thirdPartyFun calls
function thirdPartyAsyncFun() {
console.log('thirdPartyAsyncFun() called.');
return new Promise((resolve, reject) => {
throw new Error('Error Message!')
});
}
// a third-party function I want to call
function thirdPartyFun() {
console.log('thirdPartyFun() called.');
thirdPartyAsyncFun();
}
// my function
async function myLocalFun() {
try {
// I want to catch any errors this is throwing,
// but calling this produces 'Uncaught (in promise) Error'
// in the browser when there are errors
thirdPartyFun();
// This would work, but I can't call thirdPartyAsyncFun directly
// await thirdPartyAsyncFun();
} catch (er) {
// I want this to get called, but it doesn't!
console.log(er.message)
}
}
myLocalFun();
上面的jsfiddle。
【问题讨论】:
-
这是一个错误。要求库的提供者修复他们的代码并从暴露的
thirdPartyFun返回承诺,以便您可以处理他们的错误。
标签: javascript error-handling async-await