Files
2026-04-23 18:58:13 +08:00

50 lines
1.2 KiB
TypeScript

'use client';
import { Component, type ReactNode } from 'react';
type Props = {
children: ReactNode;
fallback?: ReactNode;
};
type 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 };
}
componentDidCatch(error: Error, info: React.ErrorInfo) {
console.error('[ErrorBoundary]', error, info.componentStack);
}
render() {
if (this.state.hasError) {
if (this.props.fallback) {
return this.props.fallback;
}
return (
<div className="flex min-h-[200px] flex-col items-center justify-center gap-3 p-6 text-center">
<p className="text-sm text-neutral-600"></p>
<button
type="button"
className="rounded bg-neutral-900 px-3 py-1.5 text-sm text-white hover:bg-neutral-800"
onClick={() => this.setState({ hasError: false, error: null })}
>
</button>
</div>
);
}
return this.props.children;
}
}