Skip to content

Commit

Permalink
Add error boundary
Browse files Browse the repository at this point in the history
  • Loading branch information
liambai committed Oct 31, 2024
1 parent 8c1b04a commit ce3b699
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 6 deletions.
15 changes: 9 additions & 6 deletions viz/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@ import "./App.css";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import LandingPage from "./components/LandingPage";
import SAEVisualizer from "./SAEVisualizer";
import ErrorBoundary from "./components/ErrorBoundary";

function App() {
return (
<Router>
<Routes>
<Route path="/" element={<LandingPage />} />
<Route path="/sae-visualizer" element={<SAEVisualizer />} />
</Routes>
</Router>
<ErrorBoundary>
<Router>
<Routes>
<Route path="/" element={<LandingPage />} />
<Route path="/sae-visualizer" element={<SAEVisualizer />} />
</Routes>
</Router>
</ErrorBoundary>
);
}

Expand Down
43 changes: 43 additions & 0 deletions viz/src/components/ErrorBoundary.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Component, ErrorInfo, ReactNode } from "react";

interface Props {
children: ReactNode;
fallback?: ReactNode;
}

interface State {
hasError: boolean;
error?: Error;
}

class ErrorBoundary extends Component<Props, State> {
public state: State = {
hasError: false,
};

public static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}

public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error("Error caught by boundary:", error);
console.error("Error info:", errorInfo);
}

public render() {
if (this.state.hasError) {
return (
this.props.fallback || (
<div className="p-4 rounded-lg bg-red-50 border border-red-200">
<h2 className="text-red-800 font-semibold mb-2">Something went wrong</h2>
<p className="text-red-600">{this.state.error?.message}</p>
</div>
)
);
}

return this.props.children;
}
}

export default ErrorBoundary;

0 comments on commit ce3b699

Please sign in to comment.