From b57cdb256179bf79f226884403aa6ec31d925b33 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 3 Nov 2025 20:18:32 -0600 Subject: [PATCH] Add an error boundary --- package-lock.json | 13 +++ package.json | 1 + src/App.tsx | 71 +++++++------ src/components/ErrorBoundary.test.tsx | 142 ++++++++++++++++++++++++++ src/components/ErrorBoundary.tsx | 131 ++++++++++++++++++++++++ 5 files changed, 324 insertions(+), 34 deletions(-) create mode 100644 src/components/ErrorBoundary.test.tsx create mode 100644 src/components/ErrorBoundary.tsx diff --git a/package-lock.json b/package-lock.json index 453e7c18..e62417e4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -74,6 +74,7 @@ "react": "^18.3.1", "react-day-picker": "^8.10.1", "react-dom": "^18.3.1", + "react-error-boundary": "^6.0.0", "react-hook-form": "^7.53.0", "react-i18next": "^15.7.3", "react-markdown": "^10.1.0", @@ -12382,6 +12383,18 @@ "react": "^18.3.1" } }, + "node_modules/react-error-boundary": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/react-error-boundary/-/react-error-boundary-6.0.0.tgz", + "integrity": "sha512-gdlJjD7NWr0IfkPlaREN2d9uUZUlksrfOx7SX62VRerwXbMY6ftGCIZua1VG1aXFNOimhISsTq+Owp725b9SiA==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.12.5" + }, + "peerDependencies": { + "react": ">=16.13.1" + } + }, "node_modules/react-hook-form": { "version": "7.56.1", "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.56.1.tgz", diff --git a/package.json b/package.json index ffa71029..6fd5da25 100644 --- a/package.json +++ b/package.json @@ -87,6 +87,7 @@ "react": "^18.3.1", "react-day-picker": "^8.10.1", "react-dom": "^18.3.1", + "react-error-boundary": "^6.0.0", "react-hook-form": "^7.53.0", "react-i18next": "^15.7.3", "react-markdown": "^10.1.0", diff --git a/src/App.tsx b/src/App.tsx index d27144a0..f2ce22d3 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -26,6 +26,7 @@ import { cleanupTmpDirectory } from '@/lib/tmpCleanup'; import { DynamicFavicon } from '@/components/DynamicFavicon'; import { OfflineIndicator } from '@/components/OfflineIndicator'; import { PWAUpdatePrompt } from '@/components/PWAUpdatePrompt'; +import { ErrorBoundary } from '@/components/ErrorBoundary'; import AppRouter from './AppRouter'; @@ -134,40 +135,42 @@ function FSCleanupHandler() { export function App() { return ( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ); } diff --git a/src/components/ErrorBoundary.test.tsx b/src/components/ErrorBoundary.test.tsx new file mode 100644 index 00000000..22034e5f --- /dev/null +++ b/src/components/ErrorBoundary.test.tsx @@ -0,0 +1,142 @@ +import React from 'react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { ErrorBoundary } from './ErrorBoundary'; + +// Component that throws an error +function ThrowError({ shouldThrow }: { shouldThrow: boolean }) { + if (shouldThrow) { + throw new Error('Test error message'); + } + return
No error
; +} + +describe('ErrorBoundary', () => { + // Suppress console.error during tests to avoid noise + const originalError = console.error; + beforeEach(() => { + console.error = vi.fn(); + }); + + afterEach(() => { + console.error = originalError; + }); + + it('renders children when there is no error', () => { + render( + +
Test content
+
+ ); + + expect(screen.getByText('Test content')).toBeInTheDocument(); + }); + + it('renders error UI when child component throws', () => { + render( + + + + ); + + expect(screen.getByText('Something went wrong')).toBeInTheDocument(); + expect(screen.getByText('Test error message')).toBeInTheDocument(); + }); + + it('renders custom fallback when provided as ReactNode', () => { + const customFallback =
Custom error UI
; + + render( + + + + ); + + expect(screen.getByText('Custom error UI')).toBeInTheDocument(); + }); + + it('renders custom fallback when provided as function', () => { + const customFallback = ({ error }: { error: Error }) => ( +
Error: {error.message}
+ ); + + render( + + + + ); + + expect(screen.getByText('Error: Test error message')).toBeInTheDocument(); + }); + + it('calls onError callback when error occurs', () => { + const onError = vi.fn(); + + render( + + + + ); + + expect(onError).toHaveBeenCalledWith( + expect.any(Error), + expect.objectContaining({ + componentStack: expect.any(String), + }) + ); + }); + + it('has a Try Again button that attempts to reset', async () => { + const user = userEvent.setup(); + const onError = vi.fn(); + + render( + + + + ); + + // Error UI should be visible + expect(screen.getByText('Something went wrong')).toBeInTheDocument(); + expect(onError).toHaveBeenCalledTimes(1); + + // Try Again button should be present and clickable + const tryAgainButton = screen.getByRole('button', { name: /try again/i }); + expect(tryAgainButton).toBeInTheDocument(); + + // Clicking it will attempt to reset and re-render + // Since our component still throws, it will catch the error again + await user.click(tryAgainButton); + + // The error boundary catches the error again (expected behavior) + expect(onError).toHaveBeenCalledTimes(2); + }); + + it('shows action buttons in error state', () => { + render( + + + + ); + + expect(screen.getByRole('button', { name: /try again/i })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /reload page/i })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /go home/i })).toBeInTheDocument(); + }); + + it('shows stack trace in development mode', () => { + const originalEnv = process.env.NODE_ENV; + process.env.NODE_ENV = 'development'; + + render( + + + + ); + + expect(screen.getByText('Stack Trace')).toBeInTheDocument(); + + process.env.NODE_ENV = originalEnv; + }); +}); diff --git a/src/components/ErrorBoundary.tsx b/src/components/ErrorBoundary.tsx new file mode 100644 index 00000000..d7db03c2 --- /dev/null +++ b/src/components/ErrorBoundary.tsx @@ -0,0 +1,131 @@ +import { ReactNode } from 'react'; +import { ErrorBoundary as ReactErrorBoundary, FallbackProps } from 'react-error-boundary'; +import { Button } from '@/components/ui/button'; +import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'; +import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'; +import { AlertTriangle, RefreshCw, Home } from 'lucide-react'; +import { getSentryInstance } from '@/lib/sentry'; + +interface ErrorBoundaryProps { + children: ReactNode; + fallback?: ReactNode | ((props: FallbackProps) => ReactNode); + onError?: (error: Error, info: { componentStack: string | null }) => void; + /** Whether to report errors to Sentry (default: true) */ + reportToSentry?: boolean; +} + +/** + * Default error fallback component + */ +function ErrorFallback({ error }: FallbackProps) { + const handleReload = () => { + window.location.reload(); + }; + + const handleGoHome = () => { + window.location.href = '/'; + }; + + return ( +
+ + +
+
+ +
+
+ Something went wrong + + We encountered an unexpected error. Don't worry, your data is safe. + +
+
+
+ + + + + Error Details + + {error.message} + + + + {process.env.NODE_ENV === 'development' && error.stack && ( +
+ + Stack Trace + +
+                {error.stack}
+              
+
+ )} +
+ + + + + +
+
+ ); +} + +/** + * Error Boundary component that catches React rendering errors and displays a fallback UI. + * Prevents the entire app from crashing when a component throws an error. + * + * Built on top of react-error-boundary for robust error handling. + */ +export function ErrorBoundary({ + children, + fallback, + onError, + reportToSentry = true, +}: ErrorBoundaryProps) { + const handleError = (error: Error, info: { componentStack: string | null }) => { + // Log error details for debugging + console.error('ErrorBoundary caught an error:', error, info); + + // Report to Sentry if enabled + if (reportToSentry) { + const Sentry = getSentryInstance(); + if (Sentry) { + Sentry.captureException(error, { + contexts: { + react: { + componentStack: info.componentStack, + }, + }, + }); + } + } + + // Call optional error handler + onError?.(error, info); + }; + + // Determine fallback render + const fallbackRender = typeof fallback === 'function' + ? fallback + : fallback + ? () => fallback + : ErrorFallback; + + return ( + + {children} + + ); +}