你能用 try/catch 块捕获 React.js 应用程序的所有错误吗? [英] can you catch all errors of a React.js app with a try/catch block?
问题描述
我制作了一个未实时运行的 React 应用程序,使用它的人注意到偶尔会发生一些奇怪的错误.我不知道为什么或发生了什么,并且无法重现它.
I've made a react application which is not running live, and the people that use it note that very occasionally some strange error occurs. I don't know why or what happens, and can't reproduce it.
所以我想知道是否有办法将整个应用程序或其中的一部分包装在 try/catch 块中,以便我可以将错误发送到服务器上的错误日志?
So I'm wondering if there is a way to wrap the entire app, or parts of it, in a try/catch block so that I can send the errors to an error log on the server?
到目前为止,我所读到的只是您可以将整个渲染函数包装在 try/catch 中,但这不会由于用户交互而捕获任何错误,对吗?
All I've read so far is that you could wrap the entire render function in a try/catch, but that would not catch any errors due to user interation right?
推荐答案
React 16 引入了错误边界 和 componentDidCatch 生命周期方法:
React 16 introduced Error Boundaries and the componentDidCatch lifecycle method:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
// Display fallback UI
this.setState({ hasError: true });
// You can also log the error to an error reporting service
logErrorToMyService(error, info);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
然后你就可以把它当作一个普通的组件来使用了:
Then you can use it as a regular component:
<ErrorBoundary>
<MyWidget />
</ErrorBoundary>
或者你可以用 npm 包包裹你的根组件 react-error-boundary,并设置回退组件和行为.
Or you can wrap your root component with the npm package react-error-boundary, and set a fallback component and behavior.
import {ErrorBoundary} from 'react-error-boundary';
const myErrorHandler = (error: Error, componentStack: string) => {
// ...
};
<ErrorBoundary onError={myErrorHandler}>
<ComponentThatMayError />
</ErrorBoundary>
这篇关于你能用 try/catch 块捕获 React.js 应用程序的所有错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!