thread-master/frontend/src/components/ErrorBoundary.tsx

51 lines
1.5 KiB
TypeScript
Raw Normal View History

2026-06-26 16:02:06 +00:00
import { Component, type ErrorInfo, type ReactNode } from 'react'
type ErrorBoundaryProps = {
children: ReactNode
fallback?: ReactNode
}
type ErrorBoundaryState = {
hasError: boolean
message: string
}
/**
* render AI IslanderMarkdown
*
*/
export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
state: ErrorBoundaryState = { hasError: false, message: '' }
static getDerivedStateFromError(error: unknown): ErrorBoundaryState {
return { hasError: true, message: error instanceof Error ? error.message : '發生未預期錯誤' }
}
componentDidCatch(error: Error, info: ErrorInfo) {
console.error('ErrorBoundary caught error:', error, info.componentStack)
}
private handleReset = () => {
this.setState({ hasError: false, message: '' })
}
render() {
if (!this.state.hasError) return this.props.children
if (this.props.fallback) return this.props.fallback
return (
<div className="ac-slot" style={{ padding: '1.5rem', textAlign: 'center' }}>
<p className="text-ink" style={{ marginBottom: '0.75rem' }}>
</p>
<p className="text-subtle" style={{ marginBottom: '1rem', fontSize: 13 }}>
{this.state.message}
</p>
<button type="button" className="ac-btn-secondary" onClick={this.handleReset}>
</button>
</div>
)
}
}