简体   繁体   English

在全局反应应用程序中从异步 function 中捕获错误

[英]Catch the error from an async function in react application globally

I'm trying to add a global error handler so that I can catch all the errors and show some notifications to users.我正在尝试添加一个全局错误处理程序,以便我可以捕获所有错误并向用户显示一些通知。

window.addEventListener("unhandledrejection", e => {
  console.log("unhandledrejection", e);
});

window.addEventListener("error", e => {
  console.log("error", e);
});

But this seems can't catch the errors from async functions:但这似乎无法从异步函数中捕获错误:

function App() {
  async function asyncAction() {
    throw new Error("async error"); // This error can't be caught globally
  }
  function syncAction() {
    throw new Error("sync error");
  }
  return (
    <div className="App">
      <button onClick={asyncAction}>async</button>
      <button onClick={syncAction}>sync</button>
    </div>
  );
}

The code sandbox is here: CodeSandbox代码沙箱在这里: CodeSandbox

You have to await the result of the promise returned by the async function, because otherwise the error will not propagate to your global listener.您必须等待异步 function 返回的 promise 的结果,否则错误不会传播到您的全局侦听器。

It is however still possible for async functions to mistakenly swallow errors.然而,异步函数仍然有可能错误地吞下错误。 Take for example the parallel async function.以并行异步 function 为例。 If it didn't await (or return) the result of the Promise.all([]) call, any Error would not have been propagated.如果它没有等待(或返回) Promise.all([]) 调用的结果,则不会传播任何错误。 While the parallelPromise example seem simple, it does not handle errors at all.虽然 parallelPromise 示例看起来很简单,但它根本不处理错误。 Doing so would require a similar return Promise.all([]).这样做需要类似的返回 Promise.all([])。

You can read more here in the MDN web docs. 您可以在 MDN web 文档中阅读更多信息。

In your code sandbox I can catch the async error by rewriting the asyncAction function:在您的代码沙箱中,我可以通过重写 asyncAction function 来捕获异步错误:

async function asyncAction() {

let p = new Promise(()=>{throw new Error("async error"); });

p.then().catch();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM