52 lines
1.3 KiB
TypeScript
52 lines
1.3 KiB
TypeScript
// src/components/ErrorBoundary.tsx
|
|
import React, { Component, ErrorInfo, ReactNode } from 'react';
|
|
|
|
interface Props {
|
|
children: ReactNode;
|
|
}
|
|
|
|
interface State {
|
|
hasError: boolean;
|
|
error: Error | null;
|
|
errorInfo: ErrorInfo | null;
|
|
}
|
|
|
|
class ErrorBoundary extends Component<Props, State> {
|
|
public state: State = {
|
|
hasError: false,
|
|
error: null,
|
|
errorInfo: null,
|
|
};
|
|
|
|
public static getDerivedStateFromError(_: Error): State {
|
|
// Update state so the next render will show the fallback UI.
|
|
return { hasError: true, error: _, errorInfo: null };
|
|
}
|
|
|
|
public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
|
|
// You can also log the error to an error reporting service
|
|
console.error("Uncaught error:", error, errorInfo);
|
|
this.setState({ error: error, errorInfo: errorInfo });
|
|
}
|
|
|
|
public render() {
|
|
if (this.state.hasError) {
|
|
// You can render any custom fallback UI
|
|
return (
|
|
<div style={{ padding: '20px', color: 'red' }}>
|
|
<h2>Something went wrong.</h2>
|
|
<details style={{ whiteSpace: 'pre-wrap' }}>
|
|
{this.state.error && this.state.error.toString()}
|
|
<br />
|
|
{this.state.errorInfo?.componentStack}
|
|
</details>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return this.props.children;
|
|
}
|
|
}
|
|
|
|
export default ErrorBoundary;
|