【问题标题】:Catch the error from an async function in react application globally从全局反应应用程序中的异步函数中捕获错误
【发布时间】:2020-03-18 10:15:40
【问题描述】:

我正在尝试添加一个全局错误处理程序,以便我可以捕获所有错误并向用户显示一些通知。

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

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

但这似乎无法从 async 函数中捕获错误:

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>
  );
}

代码沙箱在这里:CodeSandbox

【问题讨论】:

标签: javascript reactjs error-handling


【解决方案1】:

您必须等待异步函数返回的承诺的结果,否则错误不会传播到您的全局侦听器。

然而,异步函数仍有可能误吞 错误。以并行异步功能为例。如果没有 等待(或返回) Promise.all([]) 调用的结果,任何错误 不会被传播。虽然parallelPromise 的例子似乎 很简单,它根本不处理错误!这样做需要一个 类似返回 Promise.all([])。

You can read more here in the MDN web docs.

在您的代码沙箱中,我可以通过重写 asyncAction 函数来捕获异步错误:

async function asyncAction() {

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

p.then().catch();
}

【讨论】:

    猜你喜欢
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    • 2016-05-18
    相关资源
    最近更新 更多