全局捕获React错误 [英] Capturing React Errors Globally
问题描述
我是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.
有人可以帮我吗?
推荐答案
文档引用: https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html
实施示例的真实情况:
// 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;
}
}
这篇关于全局捕获React错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!