All files / src/components ErrorBoundary.tsx

100% Statements 9/9
100% Branches 6/6
100% Functions 4/4
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53                              10x 10x       8x       19x 8x   6x                       1x                   11x      
import { Component, type ReactNode } from "react";
import { AlertCircleIcon } from "./Icons";
 
interface Props {
	children: ReactNode;
	fallback?: ReactNode;
}
 
interface State {
	hasError: boolean;
	error: Error | null;
}
 
export class ErrorBoundary extends Component<Props, State> {
	constructor(props: Props) {
		super(props);
		this.state = { hasError: false, error: null };
	}
 
	static getDerivedStateFromError(error: Error): State {
		return { hasError: true, error };
	}
 
	render() {
		if (this.state.hasError) {
			if (this.props.fallback) return this.props.fallback;
 
			return (
				<div className="flex-1 flex items-center justify-center p-8">
					<div className="text-center max-w-md">
						<AlertCircleIcon className="w-10 h-10 text-red-400 mx-auto mb-3" />
						<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">
							Something went wrong
						</h2>
						<p className="text-sm text-gray-500 dark:text-gray-400 mb-4">
							{this.state.error?.message || "An unexpected error occurred."}
						</p>
						<button
							type="button"
							onClick={() => this.setState({ hasError: false, error: null })}
							className="px-4 py-2 text-sm bg-stork-600 hover:bg-stork-700 text-white rounded-lg transition-colors"
						>
							Try Again
						</button>
					</div>
				</div>
			);
		}
 
		return this.props.children;
	}
}