|
| 1 | +import React, { Component, ReactNode, ErrorInfo } from "react"; |
| 2 | +import { View, Text, Button, StyleSheet, ScrollView } from "react-native"; |
| 3 | +import { reportError } from "@/services/errorReporting.service"; |
| 4 | + |
| 5 | +interface Props { |
| 6 | + children: ReactNode; |
| 7 | +} |
| 8 | + |
| 9 | +interface State { |
| 10 | + hasError: boolean; |
| 11 | + error: Error | null; |
| 12 | +} |
| 13 | + |
| 14 | +class ErrorBoundary extends Component<Props, State> { |
| 15 | + constructor(props: Props) { |
| 16 | + super(props); |
| 17 | + this.state = { hasError: false, error: null }; |
| 18 | + } |
| 19 | + |
| 20 | + static getDerivedStateFromError(error: Error): State { |
| 21 | + return { hasError: true, error }; |
| 22 | + } |
| 23 | + |
| 24 | + componentDidCatch(error: Error, errorInfo: ErrorInfo) { |
| 25 | + // FIX: Calling reportError with the correct 'options' object. |
| 26 | + reportError(error, { errorInfo }); |
| 27 | + } |
| 28 | + |
| 29 | + handleResetError = () => { |
| 30 | + this.setState({ hasError: false, error: null }); |
| 31 | + }; |
| 32 | + |
| 33 | + render() { |
| 34 | + if (this.state.hasError) { |
| 35 | + return ( |
| 36 | + <View style={styles.container}> |
| 37 | + <Text style={styles.title}>Oops! Something went wrong.</Text> |
| 38 | + <Text style={styles.subtitle}> |
| 39 | + Our team has been notified. Please try again. |
| 40 | + </Text> |
| 41 | + <ScrollView style={styles.errorContainer}> |
| 42 | + <Text style={styles.errorText}>{this.state.error?.toString()}</Text> |
| 43 | + </ScrollView> |
| 44 | + <Button title="Try Again" onPress={this.handleResetError} /> |
| 45 | + </View> |
| 46 | + ); |
| 47 | + } |
| 48 | + |
| 49 | + return this.props.children; |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +const styles = StyleSheet.create({ |
| 54 | + container: { |
| 55 | + flex: 1, |
| 56 | + justifyContent: "center", |
| 57 | + alignItems: "center", |
| 58 | + padding: 20, |
| 59 | + backgroundColor: "#fefefe", |
| 60 | + }, |
| 61 | + title: { |
| 62 | + fontSize: 22, |
| 63 | + fontWeight: "bold", |
| 64 | + marginBottom: 15, |
| 65 | + textAlign: "center", |
| 66 | + color: "#333", |
| 67 | + }, |
| 68 | + subtitle: { |
| 69 | + fontSize: 16, |
| 70 | + marginBottom: 20, |
| 71 | + textAlign: "center", |
| 72 | + color: "#555", |
| 73 | + }, |
| 74 | + errorContainer: { |
| 75 | + maxHeight: 200, |
| 76 | + width: "100%", |
| 77 | + backgroundColor: "#f0f0f0", |
| 78 | + borderRadius: 8, |
| 79 | + padding: 15, |
| 80 | + marginBottom: 20, |
| 81 | + }, |
| 82 | + errorText: { |
| 83 | + color: "#d32f2f", |
| 84 | + fontFamily: "monospace", |
| 85 | + }, |
| 86 | +}); |
| 87 | + |
| 88 | +export default ErrorBoundary; |
0 commit comments