Files
Reims-Go/frontend/src/components/ErrorBoundary.tsx
T

97 lines
3.1 KiB
TypeScript

import React from 'react'
import { events } from '../wails'
interface State {
error: Error | null
stack: string
}
/**
* Top-level React error boundary: prevents any uncaught render/lifecycle error
* from unmounting the entire tree into an unrecoverable blank white screen,
* reports the stack trace to the Go backend log, and offers a one-click reload.
*/
export class ErrorBoundary extends React.Component<{ children: React.ReactNode }, State> {
state: State = { error: null, stack: '' }
static getDerivedStateFromError(error: Error): Partial<State> {
return { error }
}
componentDidCatch(error: Error, info: React.ErrorInfo): void {
const stack = [error.stack, info.componentStack].filter(Boolean).join('\n').trim()
this.setState({ stack })
events.emitUIError(`ReactErrorBoundary: ${error.message}\n${stack.slice(0, 1500)}`)
}
render(): React.ReactNode {
const { error, stack } = this.state
if (!error) return this.props.children
const isZh = (document.documentElement.lang || '').toLowerCase().startsWith('zh')
return (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '100%',
padding: 24,
background: 'var(--surface-canvas, #1c1c1e)',
color: 'var(--text, #f5f5f7)',
fontFamily: 'var(--font-sans, system-ui, sans-serif)',
}}
>
<div
style={{
maxWidth: 560,
width: '100%',
padding: 20,
borderRadius: 12,
border: '1px solid var(--border, rgba(128,128,128,0.25))',
background: 'var(--surface-1, rgba(128,128,128,0.08))',
display: 'flex',
flexDirection: 'column',
gap: 12,
}}
>
<h2 style={{ margin: 0, fontSize: 16 }}>
{isZh ? '界面发生异常' : 'Interface encountered an error'}
</h2>
<p style={{ margin: 0, fontSize: 13, opacity: 0.85 }}>
{isZh
? '渲染过程出现未捕获异常,虚拟机和后台服务不受影响。你可以重新加载界面。'
: 'An unexpected UI error occurred. Running VMs and background services are unaffected.'}
</p>
<pre
style={{
margin: 0,
padding: 10,
borderRadius: 8,
fontSize: 12,
maxHeight: 180,
overflow: 'auto',
background: 'var(--surface-0, rgba(0,0,0,0.2))',
border: '1px solid var(--border, rgba(128,128,128,0.2))',
whiteSpace: 'pre-wrap',
wordBreak: 'break-word',
}}
>
{error.message || String(error)}
{stack ? `\n\n${stack}` : ''}
</pre>
<div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
<button
type="button"
className="btn btn-primary"
onClick={() => window.location.reload()}
>
{isZh ? '重新加载界面' : 'Reload UI'}
</button>
</div>
</div>
</div>
)
}
}