gpt4 book ai didi

javascript - 如何从第三方库中获取 'Uncaught (in promise) Error'?

转载 作者:行者123 更新时间:2023-12-03 08:39:14 28 4
gpt4 key购买 nike

如果我调用了一个同步的第三方函数,该函数从正在调用的异步函数中引发错误,那么如何捕获错误?

// 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

最佳答案

您的第三方功能并不像您想象的那样同步。未调用catch块,因为当您运行异步函数时,执行将继续并且不会引发异常。您将必须添加:

await thirdPartyAsyncFun();
要么
thirdPartyAsyncFun().then(() => {
/* Do here whatever you want */
}).catch(error => {
console.log(`error: ${error} `);
});
http://jsfiddle.net/quk4zwLg/1/

关于javascript - 如何从第三方库中获取 'Uncaught (in promise) Error'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63542403/

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