Files
Profeto/frontend/src/components/ErrorBoundary.tsx
T

54 lines
1.4 KiB
TypeScript

import { Component, ErrorInfo, ReactNode } from 'react'
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('Uncaught error:', error, errorInfo)
}
public render() {
if (this.state.hasError) {
if (this.props.fallback) {
return this.props.fallback
}
return (
<div className="flex min-h-screen items-center justify-center bg-paper-50 p-6">
<div className="max-w-md space-y-3 border border-ink-900 bg-paper-50 p-6 text-center">
<p className="text-2xs tracking-[0.3em] text-ink-400">EXCEPTION</p>
<h2 className="font-serif text-lg font-bold text-ink-900">页面出现错误</h2>
<p className="text-sm leading-relaxed text-ink-500">
{this.state.error?.message || '未知错误'}
</p>
<button
onClick={() => this.setState({ hasError: false, error: null })}
className="btn btn-sm"
>
重试
</button>
</div>
</div>
)
}
return this.props.children
}
}