typescriptintermediate
Error Boundary with Fallback UI
Class-based error boundary component that catches render errors and displays a customizable fallback UI.
typescriptPress ⌘/Ctrl + Shift + C to copy
import React from 'react';
interface Props {
children: React.ReactNode;
fallback?: React.ReactNode;
}
interface State {
hasError: boolean;
error: Error | null;
}
export class ErrorBoundary extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}
componentDidCatch(error: Error, info: React.ErrorInfo) {
console.error('ErrorBoundary caught:', error, info.componentStack);
}
render() {
if (this.state.hasError) {
if (this.props.fallback) return this.props.fallback;
return (
<div role="alert" style={{ padding: 16 }}>
<h2>Something went wrong</h2>
<pre style={{ whiteSpace: 'pre-wrap' }}>
{this.state.error?.message}
</pre>
<button onClick={() => this.setState({ hasError: false, error: null })}>
Try again
</button>
</div>
);
}
return this.props.children;
}
}
// Usage:
// <ErrorBoundary fallback={<p>Oops!</p>}>
// <RiskyComponent />
// </ErrorBoundary>Use Cases
- Graceful error recovery
- Production crash reporting
- Wrapping third-party components
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
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
Error Boundary with Fallback UI
Error boundary class component with customizable fallback UI, retry button, and error reporting.
Best for: Graceful error recovery
#error-boundary#error-handling
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