javascript / expert
Snippet
Granular Error Recovery with Functional Fallback Mapping
Moving beyond generic error boundaries, this pattern uses a map of fallback components keyed by error type. This allows for specific UI responses to different failure modes (e.g., NetworkError vs. ValidationError).
snippet.js
1
2
3
4
5
6
7
8
9
10
const ErrorBoundary = ({ children, fallbacks }: ErrorBoundaryProps) => {const [error, setError] = useState<Error | null>(null);if (error) {const Fallback = fallbacks[error.name] || fallbacks['default'];return <Fallback error={error} retry={() => setError(null)} />;}return <div onErrorCapture={(e) => setError(e.nativeEvent as any)}>{children}</div>;};
react
Breakdown
1
fallbacks[error.name] || fallbacks['default']
Dynamically selects the appropriate UI component based on the specific error instance caught.
2
retry={() => setError(null)}
Provides a mechanism to reset the error state and attempt to re-render the children tree.