简体   繁体   中英

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

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.

It is however still possible for async functions to mistakenly swallow errors. Take for example the parallel async function. If it didn't await (or return) the result of the Promise.all([]) call, any Error would not have been propagated. While the parallelPromise example seem simple, it does not handle errors at all. Doing so would require a similar return Promise.all([]).

You can read more here in the MDN web docs.

In your code sandbox I can catch the async error by rewriting the asyncAction function:

async function asyncAction() {

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

p.then().catch();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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