import React, { Component, ErrorInfo, ReactNode } from 'react'; import { AlertCircle, ArrowLeft, RefreshCw, Shield } from 'lucide-react'; import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { handleError } from '@/lib/errorHandler'; interface AdminErrorBoundaryProps { children: ReactNode; fallback?: ReactNode; section?: string; // e.g., "Moderation", "Users", "Settings" } type ErrorWithId = Error & { errorId: string }; interface AdminErrorBoundaryState { hasError: boolean; error: ErrorWithId | null; errorInfo: ErrorInfo | null; } /** * Admin Error Boundary Component (P0 #5) * * Specialized error boundary for admin sections. * Prevents admin panel errors from affecting the entire app. * * Usage: * ```tsx * * * * ``` */ export class AdminErrorBoundary extends Component { constructor(props: AdminErrorBoundaryProps) { super(props); this.state = { hasError: false, error: null, errorInfo: null, }; } static getDerivedStateFromError(error: Error): Partial { return { hasError: true, error: error as ErrorWithId, }; } componentDidCatch(error: Error, errorInfo: ErrorInfo) { // Log to database and get error ID for user reference const errorId = handleError(error, { action: `Admin panel error in ${this.props.section || 'unknown section'}`, metadata: { section: this.props.section, componentStack: errorInfo.componentStack, severity: 'high', }, }); this.setState({ errorInfo, error: { ...error, errorId } as ErrorWithId }); } handleRetry = () => { this.setState({ hasError: false, error: null, errorInfo: null, }); }; handleBackToDashboard = () => { window.location.href = '/admin'; }; render() { if (this.state.hasError) { if (this.props.fallback) { return this.props.fallback; } return (
Admin Panel Error {this.props.section ? `An error occurred in ${this.props.section}` : 'An error occurred in the admin panel'}
Error Details

{this.state.error?.message || 'An unexpected error occurred in the admin panel'}

{(this.state.error as any)?.errorId && (

Reference ID: {((this.state.error as any).errorId as string).slice(0, 8)}

)}

This error has been logged. If the problem persists, please contact support.

{import.meta.env.DEV && this.state.errorInfo && (
Show Stack Trace (Development Only)
                      {this.state.error?.stack}
                    
                      {this.state.errorInfo.componentStack}
                    
)}
); } return this.props.children; } }