Files
chinese-family-tree-2/components/error-boundary.tsx
T
freedakgmail 626d7dddde 0.0.0.5
2025-11-23 00:49:16 +08:00

52 lines
1.2 KiB
TypeScript

"use client"
import React from "react"
interface Props {
children: React.ReactNode
fallback?: React.ReactNode
}
interface State {
hasError: boolean
error?: Error
}
export class ErrorBoundary extends React.Component<Props, State> {
constructor(props: Props) {
super(props)
this.state = { hasError: false }
}
static getDerivedStateFromError(error: Error): State {
return { hasError: true, error }
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
console.error("ErrorBoundary 捕获错误:", error, errorInfo)
}
render() {
if (this.state.hasError) {
return (
this.props.fallback || (
<div className="p-4 border border-destructive rounded-lg bg-destructive/10">
<h3 className="text-lg font-bold text-destructive mb-2"></h3>
<p className="text-sm text-muted-foreground">
{this.state.error?.message || "未知错误"}
</p>
<button
className="mt-4 px-4 py-2 bg-primary text-primary-foreground rounded"
onClick={() => this.setState({ hasError: false })}
>
</button>
</div>
)
)
}
return this.props.children
}
}