--- name: error-boundary-creator description: Create error boundaries, error handling, and fallback UIs for React applications. Use when implementing error handling, creating fallback components, or setting up error reporting. --- # Error Boundary Creator ## Instructions When implementing error handling: 1. **Identify error-prone areas** (async operations, third-party integrations) 2. **Create appropriate error boundaries** 3. **Design fallback UIs** 4. **Set up error reporting** ## Basic Error Boundary ```tsx 'use client'; import { Component, ErrorInfo, ReactNode } from 'react'; interface Props { children: ReactNode; fallback?: ReactNode; } interface State { hasError: boolean; error?: Error; } export class ErrorBoundary extends Component { constructor(props: Props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error: Error): State { return { hasError: true, error }; } componentDidCatch(error: Error, errorInfo: ErrorInfo) { console.error('Error caught by boundary:', error, errorInfo); // Send to error reporting service // reportError(error, errorInfo); } render() { if (this.state.hasError) { return this.props.fallback || ; } return this.props.children; } } function DefaultErrorFallback({ error }: { error?: Error }) { return (

Something went wrong

{error?.message || 'An unexpected error occurred'}

); } ``` ## Error Boundary with Reset ```tsx 'use client'; import { Component, ReactNode } from 'react'; interface Props { children: ReactNode; onReset?: () => void; } interface State { hasError: boolean; error?: Error; } export class ResettableErrorBoundary extends Component { state: State = { hasError: false }; static getDerivedStateFromError(error: Error): State { return { hasError: true, error }; } reset = () => { this.props.onReset?.(); this.setState({ hasError: false, error: undefined }); }; render() { if (this.state.hasError) { return (

Oops!

{this.state.error?.message}

); } return this.props.children; } } ``` ## react-error-boundary Library ```tsx import { ErrorBoundary, FallbackProps } from 'react-error-boundary'; function ErrorFallback({ error, resetErrorBoundary }: FallbackProps) { return (

Something went wrong:

{error.message}
); } // Usage function App() { return ( { // Reset app state here }} onError={(error, info) => { // Log to error reporting service console.error(error, info); }} > ); } ``` ## Next.js Error Handling ### App Router error.tsx ```tsx // app/error.tsx (or any route segment) 'use client'; import { useEffect } from 'react'; export default function Error({ error, reset, }: { error: Error & { digest?: string }; reset: () => void; }) { useEffect(() => { // Log error to reporting service console.error(error); }, [error]); return (

Something went wrong!

); } ``` ### Global Error (app/global-error.tsx) ```tsx 'use client'; export default function GlobalError({ error, reset, }: { error: Error & { digest?: string }; reset: () => void; }) { return (

Something went wrong!

); } ``` ### Not Found (app/not-found.tsx) ```tsx import Link from 'next/link'; export default function NotFound() { return (

404

Page not found

Go home
); } ``` ## Async Error Handling ```tsx 'use client'; import { useState } from 'react'; interface AsyncState { data: T | null; error: Error | null; isLoading: boolean; } function useAsync() { const [state, setState] = useState>({ data: null, error: null, isLoading: false, }); const execute = async (promise: Promise) => { setState({ data: null, error: null, isLoading: true }); try { const data = await promise; setState({ data, error: null, isLoading: false }); return data; } catch (error) { setState({ data: null, error: error as Error, isLoading: false }); throw error; } }; return { ...state, execute }; } // Usage function DataComponent() { const { data, error, isLoading, execute } = useAsync(); const loadData = () => execute(fetchUsers()); if (isLoading) return ; if (error) return ; if (!data) return ; return ; } ``` ## Error Reporting Integration ```typescript // lib/error-reporting.ts export function reportError(error: Error, context?: Record) { // Sentry // Sentry.captureException(error, { extra: context }); // LogRocket // LogRocket.captureException(error); // Custom endpoint fetch('/api/errors', { method: 'POST', body: JSON.stringify({ message: error.message, stack: error.stack, context, timestamp: new Date().toISOString(), url: window.location.href, userAgent: navigator.userAgent, }), }).catch(console.error); } ``` ## Best Practices 1. **Wrap at route level** for page-level isolation 2. **Wrap third-party components** separately 3. **Provide meaningful fallbacks** with recovery options 4. **Log errors** to monitoring service 5. **Don't catch errors you can't handle** 6. **Test error states** in development