49 lines
1.0 KiB
TypeScript
49 lines
1.0 KiB
TypeScript
import { Component, type ErrorInfo, type ReactNode } from "react";
|
|
import { ErrorState } from "./components/EmptyState";
|
|
|
|
interface Props {
|
|
children: ReactNode;
|
|
fallback?: ReactNode;
|
|
}
|
|
|
|
interface State {
|
|
hasError: boolean;
|
|
error: Error | null;
|
|
}
|
|
|
|
export class ErrorBoundary extends Component<Props, State> {
|
|
public state: State = {
|
|
hasError: false,
|
|
error: null
|
|
};
|
|
|
|
public static getDerivedStateFromError(error: Error): State {
|
|
return { hasError: true, error };
|
|
}
|
|
|
|
public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
|
|
console.error("ErrorBoundary caught an error:", error, errorInfo);
|
|
}
|
|
|
|
public handleReset = () => {
|
|
this.setState({ hasError: false, error: null });
|
|
};
|
|
|
|
public render() {
|
|
if (this.state.hasError) {
|
|
if (this.props.fallback) {
|
|
return this.props.fallback;
|
|
}
|
|
|
|
return (
|
|
<ErrorState
|
|
message={this.state.error?.message || "An unexpected error occurred"}
|
|
onRetry={this.handleReset}
|
|
/>
|
|
);
|
|
}
|
|
|
|
return this.props.children;
|
|
}
|
|
}
|