- Hands-On Design Patterns with React Native
- Mateusz Grzesiukiewicz
- 314字
- 2021-08-13 15:13:01
Introduction to error boundaries
This is quite an overlooked feature that came with React version 16. As you should already know, JavaScript can throw errors. Such errors should not break your app, especially if it is from the financial sector. The regular imperative solution from JavaScript is a try-catch block:
try {
// helloWorld function can potentially throw error
helloWorld();
} catch (error) {
// If helloWorld throws error
// we catch it and handle gracefully
// ...
}
This approach is hard to use with JSX. Hence, the React team developed an alternative solution for React views. It's called Error Boundaries. Any class component can become an ErrorBoundary component, given that it implements the componentDidCatch function:
class AppErrorBoundary extends React.Component {
state = { hasError: false };
componentDidCatch() {
this.setState({ hasError: true });
}
render = () => (
this.state.hasError
? <Text>Something went wrong.</Text>
: this.props.children
)
}
export default () => (
<AppErrorBoundary>
<LoginForm />
</AppErrorBoundary>
)
LoginForm is now wrapped into ErrorBoundary. It catches any error that occurs while rendering LoginForm. If Error is caught, we display a short message stating that Something went wrong. We can get a real error message from the error object. However, it is not good practice to share it with the end user. Instead, send it to your analytics server:
// Chapter 2_View patterns/Example 11/ App.js
...
componentDidCatch(error) {
this.setState({
hasError: true,
errorMsg: error
});
}
render = () => (
this.state.hasError
? (
<View>
<Text>Something went wrong.</Text>
<Text>{this.state.errorMsg.toString()}</Text>
</View>
)
: this.props.children
)
...
- 小創(chuàng)客玩轉(zhuǎn)圖形化編程
- Mastering Ember.js
- Interactive Data Visualization with Python
- Mastering Entity Framework
- 編程珠璣(續(xù))
- Practical Game Design
- Podman實(shí)戰(zhàn)
- The DevOps 2.4 Toolkit
- Clojure Reactive Programming
- 單片機(jī)C語言程序設(shè)計(jì)實(shí)訓(xùn)100例
- Creating Data Stories with Tableau Public
- 智能手機(jī)故障檢測與維修從入門到精通
- 軟件測試技術(shù)
- Java設(shè)計(jì)模式深入研究
- PostgreSQL 12 High Availability Cookbook