typescriptintermediate
Error Boundary with Fallback UI
Error boundary class component with customizable fallback UI, retry button, and error reporting.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { Component, ErrorInfo, ReactNode } from 'react';
interface Props {
children: ReactNode;
fallback?: (error: Error, reset: () => void) => ReactNode;
onError?: (error: Error, errorInfo: ErrorInfo) => void;
}
interface State {
error: Error | null;
}
export class ErrorBoundaryWithFallback extends Component<Props, State> {
state: State = { error: null };
static getDerivedStateFromError(error: Error): State {
return { error };
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
this.props.onError?.(error, errorInfo);
}
reset = () => {
this.setState({ error: null });
};
render() {
if (this.state.error) {
if (this.props.fallback) {
return this.props.fallback(this.state.error, this.reset);
}
return (
<div className="p-6 bg-red-500/10 border border-red-500/20 rounded-xl text-center">
<h3 className="text-red-400 font-medium mb-2">Something went wrong</h3>
<p className="text-gray-400 text-sm mb-4">{this.state.error.message}</p>
<button
onClick={this.reset}
className="px-4 py-2 bg-red-500/20 text-red-400 rounded-lg hover:bg-red-500/30"
>
Try Again
</button>
</div>
);
}
return this.props.children;
}
}Use Cases
- Graceful error recovery
- Widget isolation
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
Error Boundary with Fallback UI
Class-based error boundary component that catches render errors and displays a customizable fallback UI.
Best for: Graceful error recovery
#error-boundary#error-handling
typescriptintermediate
React Error Boundary Component
Build a reusable error boundary with retry, fallback UI, and error reporting integration.
Best for: Preventing full-page crashes from component errors
#react#error-boundary
typescriptintermediate
Next.js Error Handling Patterns
Implement error.tsx, not-found.tsx, and global-error.tsx for comprehensive error handling.
Best for: Graceful error recovery in nested layouts
#nextjs#error-handling
typescriptintermediate
Error Handling with error.tsx and not-found.tsx
Handle errors gracefully with error.tsx boundaries and not-found.tsx pages in App Router.
Best for: error boundaries
#nextjs#error-handling