react 错误处理
When working with a component, when any error happens inside this component code React will unmount the whole React component tree, rendering nothing. This is the React way of handling crashes.
当使用一个组件时,如果该组件代码内部发生任何错误,React将卸载整个React组件树,不呈现任何内容 。 这是处理崩溃的React方法。
You don’t want errors to show up to your users. React decides to show a blank page.
您不希望错误显示给您的用户。 React决定显示一个空白页。
However, this is just the default. Having a blank page show up is only slightly better than showing cryptic messages to users, but you should have a better way.
但是,这只是默认设置。 显示空白页仅比向用户显示隐秘消息更好,但是您应该有更好的方法。
If you are in development mode, any error will trigger a detailed stack trace printed to the browser DevTools console. Not in production however, of course, where you don’t really want bugs printed out to your users.
如果处于开发模式,则任何错误都将触发打印到浏览器DevTools控制台的详细堆栈跟踪。 但是,当然不在生产中,您实际上并不希望向用户打印错误。
In production you should intercept the errors, and show some kind of helpful message to the person using the app.
在生产中,您应该拦截错误,并向使用该应用的人员显示某种有用的信息。
This is where error boundaries come into play.
这就是错误边界起作用的地方。
With an error boundary, you isolate parts of the app and handle errors locally.
使用错误边界,您可以隔离应用程序的各个部分并在本地处理错误。
An error boundary is a React component that implements the componentDidCatch()
lifecycle event, and wraps other components:
错误边界是一个React组件,它实现componentDidCatch()
生命周期事件,并包装其他组件:
class ErrorHandler extends React.Component {
constructor(props) {
super(props)
this.state = { errorOccurred: false }
}
componentDidCatch(error, info) {
this.setState({ errorOccurred: true })
logErrorToMyService(error, info)
}
render() {
return this.state.errorOccurred ? <h1>Something went wrong!</h1> : this.props.children
}
}
and in a component JSX, you use it like this:
在组件JSX中,您可以像这样使用它:
<ErrorHandler>
<SomeOtherComponent />
</ErrorHandler>
When an error happens inside SomeOtherComponent
or other child components, and in the whole components subtree that they hold, ErrorHandler
is going to intercept it, and you can handle the error gracefully.
当SomeOtherComponent
或其他子组件内部以及它们所持有的整个组件子树中发生错误时, ErrorHandler
将拦截该错误,您可以优雅地处理该错误。
In the above case which is inspired by the React official documentation we have an errorOccurred
state property that when set to true, makes the interface render the error handling UI, otherwise it renders the normal application UI tree.
在上述情况下,受React官方文档的启发,我们有一个errorOccurred
状态属性,将其设置为true时,使接口呈现错误处理UI,否则呈现常规应用程序UI树。
Inside componentDidCatch()
, which receives 2 arguments that describe the error, we also call logErrorToMyService()
which is just a stub for some function that uses a service like Sentry, Roller, Airbrake or others that can log the error in a nice way for you to see, so you don’t have to rely on users telling you there’s an error to notice a problem.
在componentDidCatch()
里面,它接收2个描述错误的参数,我们也调用logErrorToMyService()
,它只是一些函数的存根,该函数使用Sentry,Roller,Airbrake或其他可以很好地记录错误的服务您可以看到,因此您不必依靠用户告诉您存在错误来注意到问题。
react 错误处理