From ad397c33a679178ac5ffc198b9e5caf64996a561 Mon Sep 17 00:00:00 2001 From: David Edler Date: Fri, 5 Jan 2024 11:54:37 +0100 Subject: [PATCH] feat(errors) add error boundaries Signed-off-by: David Edler --- src/Root.tsx | 41 +++++++++-------- src/components/ErrorBoundary.tsx | 77 ++++++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+), 18 deletions(-) create mode 100644 src/components/ErrorBoundary.tsx diff --git a/src/Root.tsx b/src/Root.tsx index 66b1808d8c..c8b969c9aa 100644 --- a/src/Root.tsx +++ b/src/Root.tsx @@ -9,29 +9,34 @@ import { InstanceLoadingProvider } from "context/instanceLoading"; import { ProjectProvider } from "context/project"; import Events from "pages/instances/Events"; import App from "./App"; +import ErrorBoundary from "components/ErrorBoundary"; const queryClient = new QueryClient(); const Root: FC = () => { return ( - - - - - - -
- - - - -
-
-
-
-
-
-
+ + + + + + + +
+ + + + + + +
+
+
+
+
+
+
+
); }; diff --git a/src/components/ErrorBoundary.tsx b/src/components/ErrorBoundary.tsx new file mode 100644 index 0000000000..3755c39b0c --- /dev/null +++ b/src/components/ErrorBoundary.tsx @@ -0,0 +1,77 @@ +import React from "react"; +import { + CodeSnippet, + CodeSnippetBlockAppearance, + Notification, + Strip, +} from "@canonical/react-components"; +import type { PropsWithChildren } from "react"; +import { Component } from "react"; + +type Props = PropsWithChildren; + +type State = { + error?: Error; + hasError: boolean; +}; + +export default class ErrorBoundary extends Component { + constructor(props: Props) { + super(props); + this.state = { hasError: false }; + } + + static getDerivedStateFromError(error: Error) { + return { + hasError: true, + error, + }; + } + + render() { + const { error, hasError } = this.state; + const { children } = this.props; + const body = encodeURIComponent( + `\`\`\`\n${error?.stack ?? "No stack track"}\n\`\`\``, + ); + const url = `https://github.com/canonical/lxd-ui/issues/new?labels=bug&title=Error%20report&body=${body}`; + if (hasError) { + return ( + + + Something has gone wrong. If this issue persists,{" "} + + please raise an issue on GitHub. + + + + + ); + } + + return <>{children}; + } +}