# All files / src/components/error ErrorBoundary.tsx

0% Statements 0/48
0% Branches 0/27
0% Functions 0/14
0% Lines 0/46

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238

     'use client';

    import React, { Component, ErrorInfo, ReactNode } from 'react';
    import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
    import { Button } from '@/components/ui/button';
    import { Alert, AlertDescription } from '@/components/ui/alert';
    import { AlertTriangle, RefreshCw, Home, Bug } from 'lucide-react';
    import i18n from '@/lib/i18n';

    interface Props {
      children: ReactNode;
      fallback?: ReactNode;
      onError?: (error: Error, errorInfo: ErrorInfo) => void;
      showDetails?: boolean;
      resetKeys?: Array<string | number>;
      resetOnPropsChange?: boolean;
    }

    interface State {
      hasError: boolean;
      error: Error | null;
      errorInfo: ErrorInfo | null;
      eventId: string | null;
    }

    export class ErrorBoundary extends Component<Props, State> {
      private resetTimeoutId: number | null = null;

      constructor(props: Props) {
        super(props);
        this.state = {
          hasError: false,
          error: null,
          errorInfo: null,
          eventId: null};
      }

      static getDerivedStateFromError(error: Error): Partial<State> {
        // Update state so the next render will show the fallback UI
        return {
          hasError: true,
          error,
          eventId: `error_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`};
      }

      componentDidCatch(error: Error, errorInfo: ErrorInfo) {
        // Log error details
        console.error('ErrorBoundary caught an error:', error, errorInfo);

        this.setState({
          error,
          errorInfo});

        // Call custom error handler if provided
        if (this.props.onError) {
          this.props.onError(error, errorInfo);
        }

        // Report to error monitoring service (if available)
        this.reportError(error, errorInfo);
      }

      componentDidUpdate(prevProps: Props) {
        const { resetKeys, resetOnPropsChange } = this.props;
        const { hasError } = this.state;

        if (hasError && prevProps.resetKeys !== resetKeys) {
          if (resetKeys?.some((key, idx) => prevProps.resetKeys?.[idx] !== key)) {
            this.resetErrorBoundary();
          }
        }

        if (hasError && resetOnPropsChange && prevProps.children !== this.props.children) {
          this.resetErrorBoundary();
        }
      }

      resetErrorBoundary = () => {
        if (this.resetTimeoutId) {
          clearTimeout(this.resetTimeoutId);
        }

        this.setState({
          hasError: false,
          error: null,
          errorInfo: null,
          eventId: null});
      };

      handleRetry = () => {
        this.resetErrorBoundary();
      };

      handleReload = () => {
        window.location.reload();
      };

      handleGoHome = () => {
        window.location.href = '/';
      };

      reportError = (error: Error, errorInfo: ErrorInfo) => {
        // Here you would integrate with error monitoring services like Sentry
        const errorReport = {
          message: error.message,
          stack: error.stack,
          componentStack: errorInfo.componentStack,
          timestamp: new Date().toISOString(),
          userAgent: navigator.userAgent,
          url: window.location.href,
          eventId: this.state.eventId};

        // Log to console for development
        console.group('🚨 Error Report');
        console.error('Error:', error);
        console.error('Error Info:', errorInfo);
        console.error('Report:', errorReport);
        console.groupEnd();

        // In production, you would send this to your error monitoring service
        // Example: Sentry.captureException(error, { contexts: { errorInfo } });
      };

      render() {
        if (this.state.hasError) {
          // Custom fallback UI
          if (this.props.fallback) {
            return this.props.fallback;
          }

          // Default error UI
          return (
            <div className="min-h-screen flex items-center justify-center p-4 bg-gray-50">
              <Card className="w-full max-w-2xl">
                <CardHeader>
                  <div className="flex items-center gap-3">
                    <div className="p-2 bg-red-100 rounded-full">
                      <AlertTriangle className="h-6 w-6 text-red-600" />
                    </div>
                    <div>
                      <CardTitle className="text-red-900">{i18n.t('common.somethingWentWrong')}</CardTitle>
                      <CardDescription>{i18n.t('common.unexpectedErrorDescription')}</CardDescription>
                    </div>
                  </div>
                </CardHeader>
                <CardContent className="space-y-4">
                  {/* Error Message */}
                  <Alert variant="destructive">
                    <Bug className="h-4 w-4" />
                    <AlertDescription>
                      <strong>{i18n.t('common.error')}</strong> {this.state.error?.message || i18n.t('common.unknownError')}
                    </AlertDescription>
                  </Alert>

                  {/* Error Details (Development) */}
                  {this.props.showDetails && this.state.error && (
                    <details className="mt-4">
                      <summary className="cursor-pointer text-sm font-medium text-gray-700 hover:text-gray-900">
                        {i18n.t('common.technicalDetails')}
                      </summary>
                      <div className="mt-2 p-3 bg-gray-100 rounded-md">
                        <pre className="text-xs text-gray-800 whitespace-pre-wrap overflow-auto max-h-40">
                          {this.state.error.stack}
                        </pre>
                        {this.state.errorInfo && (
                          <div className="mt-2 pt-2 border-t border-gray-300">
                            <p className="text-xs font-medium text-gray-700 mb-1">{i18n.t('common.componentStack')}</p>
                            <pre className="text-xs text-gray-600 whitespace-pre-wrap overflow-auto max-h-32">
                              {this.state.errorInfo.componentStack}
                            </pre>
                          </div>
                        )}
                      </div>
                    </details>
                  )}

                  {/* Error ID */}
                  {this.state.eventId && (
                    <div className="text-xs text-gray-500">
                      {i18n.t('common.errorId')}: <code className="bg-gray-100 px-1 rounded">{this.state.eventId}</code>
                    </div>
                  )}

                  {/* Action Buttons */}
                  <div className="flex flex-wrap gap-3 pt-4">
                    <Button onClick={this.handleRetry} variant="default">
                      <RefreshCw className="h-4 w-4 mr-2" />
                      {i18n.t('common.tryAgain')}
                    </Button>
                    <Button onClick={this.handleReload} variant="outline">
                      <RefreshCw className="h-4 w-4 mr-2" />
                      {i18n.t('common.reloadPage')}
                    </Button>
                    <Button onClick={this.handleGoHome} variant="outline">
                      <Home className="h-4 w-4 mr-2" />
                      {i18n.t('common.goHome')}
                    </Button>
                  </div>

                  {/* Help Text */}
                  <div className="text-sm text-gray-600 pt-4 border-t">
                    <p>{i18n.t('common.contactSupport')}</p>
                  </div>
                </CardContent>
              </Card>
            </div>
          );
        }

        return this.props.children;
      }
    }

    // Hook for functional components to reset error boundary
    export function useErrorHandler() {
      return (error: Error, errorInfo?: ErrorInfo) => {
        console.error('Error caught by useErrorHandler:', error, errorInfo);
        throw error; // Re-throw to be caught by ErrorBoundary
      };
    }

    // Higher-order component for easier usage
    export function withErrorBoundary<P extends object>(
      Component: React.ComponentType<P>,
      errorBoundaryProps?: Omit<Props, 'children'>
    ) {
      const WrappedComponent = (props: P) => (
        <ErrorBoundary {...errorBoundaryProps}>
          <Component {...props} />
        </ErrorBoundary>
      );

      WrappedComponent.displayName = `withErrorBoundary(${Component.displayName || Component.name})`;
      return WrappedComponent;
    }

    export default ErrorBoundary;