32 lines
851 B
TypeScript
32 lines
851 B
TypeScript
import React from 'react'
|
|
|
|
type State = { hasError: boolean; error?: Error }
|
|
|
|
export default class ErrorBoundary extends React.Component<React.PropsWithChildren, State> {
|
|
constructor(props: React.PropsWithChildren) {
|
|
super(props)
|
|
this.state = { hasError: false }
|
|
}
|
|
|
|
static getDerivedStateFromError(error: Error) {
|
|
return { hasError: true, error }
|
|
}
|
|
|
|
componentDidCatch(error: Error, info: unknown) {
|
|
// send to remote logging if desired
|
|
console.error('Uncaught error in component tree:', error, info)
|
|
}
|
|
|
|
render() {
|
|
if (this.state.hasError) {
|
|
return (
|
|
<div style={{ padding: 24 }}>
|
|
<h1 style={{ color: '#b91c1c' }}>Something went wrong</h1>
|
|
<pre style={{ whiteSpace: 'pre-wrap' }}>{String(this.state.error)}</pre>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
return this.props.children
|
|
}
|
|
}
|