ErrorBoundary.tsx
2.05 KB
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
54
55
56
57
58
59
60
import { Component, type ReactNode } from 'react';
import { AlertTriangle, RotateCcw } from 'lucide-react';
interface Props {
children: ReactNode;
}
interface State {
error: Error | null;
}
/**
* Top-level error boundary. A render error in any single page would otherwise
* unmount the whole React tree (blank screen, every menu "unreachable").
* This keeps the shell alive and shows a recoverable panel instead.
*/
export class ErrorBoundary extends Component<Props, State> {
state: State = { error: null };
static getDerivedStateFromError(error: Error): State {
return { error };
}
componentDidCatch(error: Error, info: unknown) {
// eslint-disable-next-line no-console
console.error('[ErrorBoundary]', error, info);
}
handleReset = () => {
this.setState({ error: null });
};
render() {
if (this.state.error) {
return (
<div className="flex h-screen w-screen items-center justify-center bg-background p-6">
<div className="w-full max-w-md rounded-2xl border border-border bg-card p-8 text-center shadow-xl">
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-rose-500/10 text-rose-400">
<AlertTriangle className="h-6 w-6" />
</div>
<h2 className="text-lg font-semibold">页面出错了</h2>
<p className="mt-2 break-words text-sm text-muted-foreground">
{this.state.error.message || '发生未知错误'}
</p>
<button
onClick={this.handleReset}
className="mt-5 inline-flex items-center gap-2 rounded-xl bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-transform hover:scale-[1.02]"
>
<RotateCcw className="h-4 w-4" />
重试
</button>
<p className="mt-3 text-xs text-muted-foreground">
应用其余部分仍正常运行,可尝试切换其他菜单。
</p>
</div>
</div>
);
}
return this.props.children;
}
}