52 lines
1.2 KiB
TypeScript
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
|
|
}
|
|
}
|