【发布时间】: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
【问题讨论】:
-
@JesperJohansson “错误边界不会在事件处理程序中捕获错误。” reactjs.org/docs/error-boundaries.html#how-about-event-handlers
标签: javascript reactjs error-handling