test handling errors

This commit is contained in:
Antoine M 2024-05-15 09:59:19 +02:00
parent d8fd374b12
commit 220afb8d10
2 changed files with 38 additions and 1 deletions

View File

@ -0,0 +1,34 @@
import React from "react";
export class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
componentDidCatch(error, info) {
// Example "componentStack":
// in ComponentThatThrows (created by App)
// in ErrorBoundary (created by App)
// in div (created by App)
// in App
// logErrorToMyService(error, info.componentStack);
console.log(error);
console.log(info.componentStack);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return this.props.fallback;
}
return this.props.children;
}
}

View File

@ -7,6 +7,7 @@ import { BrowserRouter, Route, Routes, useLocation } from "react-router-dom";
import { AnimatePresence } from "framer-motion"; import { AnimatePresence } from "framer-motion";
import Home from "./pages/Home.jsx"; import Home from "./pages/Home.jsx";
import Profile from "./pages/Profile.jsx"; import Profile from "./pages/Profile.jsx";
import {ErrorBoundary} from "./components/ErrorBoundary.jsx";
const root = ReactDOM.createRoot(document.getElementById("root")); const root = ReactDOM.createRoot(document.getElementById("root"));
@ -14,7 +15,9 @@ root.render(
<React.StrictMode> <React.StrictMode>
<UserContextProvider> <UserContextProvider>
<BrowserRouter> <BrowserRouter>
<App /> <ErrorBoundary fallback={<p>Something went wrong</p>}>
<App />
</ErrorBoundary>
</BrowserRouter> </BrowserRouter>
</UserContextProvider> </UserContextProvider>
</React.StrictMode> </React.StrictMode>