From b32b3a5af3440e8b4ae5403bfafa7886e4e72fe9 Mon Sep 17 00:00:00 2001 From: Abdullah Atta Date: Wed, 7 Feb 2024 13:33:40 +0500 Subject: [PATCH] web: trigger error boundary on unhandled errors --- apps/web/src/hooks/use-database.ts | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/apps/web/src/hooks/use-database.ts b/apps/web/src/hooks/use-database.ts index cd82777d2..892196fc0 100644 --- a/apps/web/src/hooks/use-database.ts +++ b/apps/web/src/hooks/use-database.ts @@ -19,6 +19,7 @@ along with this program. If not, see . import { useEffect, useState } from "react"; import { initializeDatabase } from "../common/db"; +import { useErrorBoundary } from "react-error-boundary"; import "allotment/dist/style.css"; import "../utils/analytics"; import "../app.css"; @@ -32,9 +33,28 @@ const memory = { }; export default function useDatabase(persistence: "db" | "memory" = "db") { const [isAppLoaded, setIsAppLoaded] = useState(memory.isDatabaseLoaded); + const { showBoundary } = useErrorBoundary(); useEffect(() => { - loadDatabase(persistence).then(() => setIsAppLoaded(true)); + loadDatabase(persistence) + .then(() => setIsAppLoaded(true)) + .catch((e) => showBoundary(e)); + + function handleError(e: ErrorEvent) { + showBoundary(e.error); + } + function handleUnhandledRejection(e: PromiseRejectionEvent) { + showBoundary(e.reason); + } + window.addEventListener("unhandledrejection", handleUnhandledRejection); + window.addEventListener("error", handleError); + return () => { + window.removeEventListener( + "unhandledrejection", + handleUnhandledRejection + ); + window.removeEventListener("error", handleError); + }; }, [persistence]); return [isAppLoaded];