code-review-fix task 10.1: create ErrorBoundary component with fallback UI
This commit is contained in:
parent
43b6b5da9e
commit
081a46638b
1 changed files with 66 additions and 0 deletions
66
src/components/ErrorBoundary.tsx
Normal file
66
src/components/ErrorBoundary.tsx
Normal file
|
|
@ -0,0 +1,66 @@
|
||||||
|
"use client";
|
||||||
|
|
||||||
|
import React, { Component, ErrorInfo, ReactNode } from "react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
children: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface State {
|
||||||
|
hasError: boolean;
|
||||||
|
error: Error | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
class ErrorBoundary extends Component<Props, State> {
|
||||||
|
constructor(props: Props) {
|
||||||
|
super(props);
|
||||||
|
this.state = { hasError: false, error: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
static getDerivedStateFromError(error: Error): State {
|
||||||
|
return { hasError: true, error };
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidCatch(error: Error, errorInfo: ErrorInfo): void {
|
||||||
|
console.error("ErrorBoundary caught an error:", error, errorInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
handleTryAgain = (): void => {
|
||||||
|
this.setState({ hasError: false, error: null });
|
||||||
|
};
|
||||||
|
|
||||||
|
handleReload = (): void => {
|
||||||
|
window.location.reload();
|
||||||
|
};
|
||||||
|
|
||||||
|
render(): ReactNode {
|
||||||
|
if (this.state.hasError) {
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen flex-col items-center justify-center gap-6 p-8 text-center">
|
||||||
|
<div className="flex flex-col items-center gap-3">
|
||||||
|
<h2 className="text-2xl font-semibold text-destructive">
|
||||||
|
Something went wrong
|
||||||
|
</h2>
|
||||||
|
{this.state.error && (
|
||||||
|
<p className="max-w-md text-sm text-muted-foreground">
|
||||||
|
{this.state.error.message}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<Button variant="outline" onClick={this.handleTryAgain}>
|
||||||
|
Try Again
|
||||||
|
</Button>
|
||||||
|
<Button onClick={this.handleReload}>Reload</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.props.children;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export { ErrorBoundary };
|
||||||
|
export default ErrorBoundary;
|
||||||
Loading…
Add table
Add a link
Reference in a new issue