【问题标题】:How can you catch 'Uncaught (in promise) Error' from third party library?您如何从第三方库中捕获“未捕获(承诺)错误”?
【发布时间】: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


【解决方案1】:

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

await thirdPartyAsyncFun();

或者

thirdPartyAsyncFun().then(() => {
/* Do here whatever you want */
}).catch(error => {
console.log(`error: ${error} `);
});

http://jsfiddle.net/quk4zwLg/1/

【讨论】:

  • 等待thirdPartyAsyncFun();没有捕捉到错误。另外,我不能使用您的第二种方法,因为它是我无法更改的第三方功能。
猜你喜欢
  • 1970-01-01
  • 2021-11-28
  • 2022-12-19
  • 1970-01-01
  • 2023-02-06
  • 2018-05-12
  • 2019-08-20
  • 2022-09-24
  • 2023-01-30
相关资源
最近更新 更多