全局捕获 React 错误 [英] Capturing React Errors Globally

查看:92
本文介绍了全局捕获 React 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 React 的新手.我想捕获所有未捕获的反应和意外错误/警告,我想将错误记录到外部 api.我知道它可以通过 Try Catch 方法实现,但我计划在全局范围内使用它,以便其他开发人员无需每次都编写代码.

I'm new to React. I want to capture all react uncaught and unexpected errors/warnings and i would like to log the errors to an external api. I know its possible by Try Catch method but I'm planning to have it globally so that other developer need not to write the code each and every time.

我尝试了 window.onerror/addEventListener('error', function(e){},它只捕获 Javascript 错误但不响应错误.

I tried window.onerror/addEventListener('error', function(e){} which only captures the Javascript errors but not react errors.

这类似于以下帖子我如何处理异常?.但是给出的解决方案不能满足我的需求.

This is similar to following post How do I handle exceptions?. But the solution given didn't meet my needs.

有人可以帮助我吗?

推荐答案

需要注意的是,async 方法中的错误不会被捕获,例如 async componentDidMount错误边界.

A thing to note is that errors in async methods like async componentDidMount won't be caught in a error boundary.

https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event

由于并非所有错误都会被捕获,因此我们决定在我们的项目中使用 vanilla JavaScript window.onerrorwindow.onunhandledrejection.

Since not all errors will be caught we decided to use vanilla JavaScript window.onerror and window.onunhandledrejection in our project.

完整的问答:

https://stackoverflow.com/a/64319415/3850405

这篇关于全局捕获 React 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆