- 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
)
...
- Objective-C應用開發全程實錄
- Android Application Development Cookbook(Second Edition)
- Learning SAP Analytics Cloud
- C語言實驗指導及習題解析
- Windows Server 2016 Automation with PowerShell Cookbook(Second Edition)
- R大數據分析實用指南
- Python忍者秘籍
- 用戶體驗可視化指南
- Software-Defined Networking with OpenFlow(Second Edition)
- 從“1”開始3D編程
- Joomla!Search Engine Optimization
- 基于MATLAB的控制系統仿真及應用
- 例說FPGA:可直接用于工程項目的第一手經驗
- Splunk Essentials
- Getting Started with the Lazarus IDE