44 lines
1.2 KiB
TypeScript
44 lines
1.2 KiB
TypeScript
import { Component, ErrorInfo, ReactNode } from "react";
|
|
|
|
interface Props {
|
|
children: ReactNode;
|
|
}
|
|
|
|
interface State {
|
|
hasError: boolean;
|
|
error: Error | null;
|
|
}
|
|
|
|
export class ErrorBoundary extends Component<Props, State> {
|
|
state: State = { hasError: false, error: null };
|
|
|
|
static getDerivedStateFromError(error: Error): State {
|
|
return { hasError: true, error };
|
|
}
|
|
|
|
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
|
|
console.error("App error:", error, errorInfo);
|
|
}
|
|
|
|
render() {
|
|
if (this.state.hasError && this.state.error) {
|
|
return (
|
|
<div style={{ padding: "2rem", maxWidth: 900, margin: "0 auto", fontFamily: "Arial", color: "#333" }}>
|
|
<h1 style={{ color: "#c0392b", marginBottom: "1rem" }}>Something went wrong</h1>
|
|
<pre style={{ background: "#f7f7f7", padding: "1rem", overflow: "auto", fontSize: 13 }}>
|
|
{this.state.error.message}
|
|
</pre>
|
|
<button
|
|
type="button"
|
|
onClick={() => this.setState({ hasError: false, error: null })}
|
|
style={{ marginTop: "1rem", padding: "8px 16px", cursor: "pointer" }}
|
|
>
|
|
Try again
|
|
</button>
|
|
</div>
|
|
);
|
|
}
|
|
return this.props.children;
|
|
}
|
|
}
|