简体   繁体   English

全局捕获 React 错误

[英]Capturing React Errors Globally

I'm new to React.我是 React 的新手。 I want to capture all react uncaught and unexpected errors/warnings and i would like to log the errors to an external api.我想捕获所有未捕获和意外错误/警告的反应,我想将错误记录到外部 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.我知道它可以通过 Try Catch 方法实现,但我计划在全局范围内使用它,以便其他开发人员无需每次都编写代码。

I tried window.onerror/addEventListener('error', function(e){} which only captures the Javascript errors but not react errors.我尝试了window.onerror/addEventListener('error', function(e){} ,它只捕获 Javascript 错误但不响应错误。

This is similar to following post How do I handle exceptions?这类似于以下帖子如何处理异常? . . But the solution given didn't meet my needs.但是给出的解决方案不能满足我的需求。

Can someone help me on this?有人可以帮我吗?

Doc refs: https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html文档参考: https : //reactjs.org/blog/2017/07/26/error-handling-in-react-16.html

Real case of implementation example:实现实例的真实案例:

 // app.js const MOUNT_NODE = document.getElementById('app'); const render = (messages) => { ReactDOM.render( <Provider store={store}> <LanguageProvider messages={messages}> <ConnectedRouter history={history}> <ErrorBoundary> <App /> </ErrorBoundary> </ConnectedRouter> </LanguageProvider> </Provider>, MOUNT_NODE ); }; // ErrorBoundary component export default class ErrorBoundary { constructor(props) { super(props); this.state = { hasError: false }; } componentDidCatch(error, info) { // Display fallback UI this.setState({ hasError: true }); } render() { if (this.state.hasError) { return ( <div> // error message </div> ); } return this.props.children; } }

A thing to note is that errors in async methods like async componentDidMount won't be caught in a error boundary .需要注意的是,像async componentDidMount这样的async方法中的error boundary不会被error boundary捕获。

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

Since not all errors will be caught we decided to use vanilla JavaScript window.onerror and window.onunhandledrejection in our project.由于并非所有错误都会被捕获,我们决定在我们的项目中使用 vanilla JavaScript window.onerrorwindow.onunhandledrejection

Complete question and answer:完整问答:

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

This will help: https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html这将有所帮助: https : //reactjs.org/blog/2017/07/26/error-handling-in-react-16.html

Basically, with React 16 and above you can use componentDidCatch() lifecycle method in your parent most component to log all the uncaught exceptions.基本上,在 React 16 及更高版本中,您可以在父组件中使用componentDidCatch()生命周期方法来记录所有未捕获的异常。

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

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