We want to disable the classic white screen when the app somehow crashes. We are using the react-native-exception-handler module and it catches some errors but not all aparently. When we catch those errors we notify ourselves and do restart the app. But sometimes there is some errors (like when the application is fed some data by the server that it doesn't expect), that trigger the white screen. We would prefer that our clients stay with the app frozen or with a notification that they would have to restart the app, than with a "random" white screen. Can it be done?
here is a demo:https://snack.expo.io/@carloscuesta/react-native-error-boundary
you can use react-native-error-boundary
yarn add react-native-error-boundary
this dont handle native error but handle all error of js level. you can combine use this package with react-native-exception-handler.
import * as React from 'react';
import { Button, Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
import ErrorBoundary from 'react-native-error-boundary';
import ComponentWithError from './ComponentWithError'
const App = () => {
const [isErrorComponentVisible, setIsErrorComponentVisible] = React.useState(false)
return (
<ErrorBoundary>
<View style={styles.container}>
<Text style={styles.icon}>🐛</Text>
<Text style={styles.title}>
react-native-error-boundary
</Text>
<Text style={styles.text}>
Click on the following button to render a component that will throw an error.
</Text>
<Button title='Throw error' onPress={() => setIsErrorComponentVisible(true)} />
{isErrorComponentVisible && <ComponentWithError />}
</View>
</ErrorBoundary>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
textAlign: 'center',
},
title: {
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
icon: {
fontSize: 48
},
text: {
marginVertical: 16
}
});
export default App
You can use error boundary. Wrap your root app inside ErrorBoundary, then you'll be able to catch error in any of the components:
<ErrorBoundary>
<App />
</ErrorBoundary>
and for ErrorBoundary Component you could do something like this
export default class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { error: null, errorInfo: null };
}
componentDidCatch(error, errorInfo) {
// Catch errors in any components below and re-render with error message
this.setState({
error: error,
errorInfo: errorInfo,
});
// You can also send notification based on the error catch
sendNotification("Kindly Restart App");
}
render() {
if (this.state.errorInfo) {
// Error path
return (
<View>
<Text>Some thing went wrong .. Kindly Restart the Application</Text>
</View>
);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With