Skip to content

TagSpaces is an offline, open source, document manager with tagging support

feat: integrated modern error handling with bondaries

Ilian Sapundshievd1ba29a5606a
diff --git a/src/renderer/components/EntryContainer.tsx b/src/renderer/components/EntryContainer.tsx
index 71480ba56..6013401b2 100644
--- a/src/renderer/components/EntryContainer.tsx
+++ b/src/renderer/components/EntryContainer.tsx
@@ -20,6 +20,7 @@ import AppConfig from '-/AppConfig';
import EntryContainerNav from '-/components/EntryContainerNav';
import EntryContainerTabs from '-/components/EntryContainerTabs';
import EntryContainerTitle from '-/components/EntryContainerTitle';
+import { ErrorBoundary } from '-/components/ErrorBoundary';
import FileView from '-/components/FileView';
import { Splitter } from '-/components/Splitter';
import { useResolveConflictContext } from '-/components/dialogs/hooks/useResolveConflictContext';
@@ -600,13 +601,27 @@ function EntryContainer() {
);
const fileView = openedEntry.isFile ? (
- <FileView
- key="FileViewID"
- fileViewer={fileViewer}
- fileViewerContainer={fileViewerContainer}
- height="100%"
- handleMessage={handleMessage}
- />
+ <ErrorBoundary
+ title={t('core:error')}
+ label={openedEntry.path}
+ resetKeys={[openedEntry.path]}
+ onError={() =>
+ showNotification(
+ t('core:error'),
+ 'error',
+ true,
+ 'fileViewCrashTID',
+ )
+ }
+ >
+ <FileView
+ key="FileViewID"
+ fileViewer={fileViewer}
+ fileViewerContainer={fileViewerContainer}
+ height="100%"
+ handleMessage={handleMessage}
+ />
+ </ErrorBoundary>
) : null;
if (openedEntry.isFile && isPanelOpened) {
diff --git a/src/renderer/components/ErrorBoundary.tsx b/src/renderer/components/ErrorBoundary.tsx
new file mode 100644
index 000000000..9dbe3f3c5
--- /dev/null
+++ b/src/renderer/components/ErrorBoundary.tsx
@@ -0,0 +1,154 @@
+/**
+ * TagSpaces - universal file and folder organizer
+ * Copyright (C) 2026-present TagSpaces GmbH
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License (version 3) as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+import i18n from '-/services/i18n';
+import Alert from '@mui/material/Alert';
+import Box from '@mui/material/Box';
+import Typography from '@mui/material/Typography';
+import React from 'react';
+
+export type ErrorBoundaryRenderFallback = (
+ error: Error,
+ reset: () => void,
+) => React.ReactNode;
+
+type Props = {
+ children: React.ReactNode;
+ fallback?: React.ReactNode | ErrorBoundaryRenderFallback;
+ onError?: (error: Error, info: React.ErrorInfo) => void;
+ resetKeys?: ReadonlyArray<unknown>;
+ title?: string;
+ label?: string;
+};
+
+type State = {
+ hasError: boolean;
+ error?: Error;
+ info?: React.ErrorInfo;
+};
+
+function shallowDiffer(
+ a: ReadonlyArray<unknown> | undefined,
+ b: ReadonlyArray<unknown> | undefined,
+) {
+ if (a === b) return false;
+ if (!a || !b) return true;
+ if (a.length !== b.length) return true;
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return true;
+ return false;
+}
+
+export class ErrorBoundary extends React.Component<Props, State> {
+ state: State = { hasError: false };
+
+ static getDerivedStateFromError(error: Error): State {
+ return { hasError: true, error };
+ }
+
+ componentDidCatch(error: Error, info: React.ErrorInfo) {
+ console.error('ErrorBoundary caught:', this.props.label ?? '', error, info);
+ this.setState({ info });
+ this.props.onError?.(error, info);
+ }
+
+ componentDidUpdate(prevProps: Props) {
+ if (
+ this.state.hasError &&
+ shallowDiffer(prevProps.resetKeys, this.props.resetKeys)
+ ) {
+ this.reset();
+ }
+ }
+
+ reset = () => {
+ this.setState({ hasError: false, error: undefined, info: undefined });
+ };
+
+ render() {
+ if (!this.state.hasError) return this.props.children;
+ const { fallback } = this.props;
+ if (typeof fallback === 'function') {
+ return (fallback as ErrorBoundaryRenderFallback)(
+ this.state.error as Error,
+ this.reset,
+ );
+ }
+ if (fallback !== undefined) return fallback;
+ return (
+ <DefaultErrorFallback
+ error={this.state.error}
+ info={this.state.info}
+ title={this.props.title}
+ label={this.props.label}
+ />
+ );
+ }
+}
+
+function DefaultErrorFallback({
+ error,
+ info,
+ title,
+ label,
+}: {
+ error?: Error;
+ info?: React.ErrorInfo;
+ title?: string;
+ label?: string;
+}) {
+ const message = error?.message || i18n.t('core:unexpectedError');
+ const heading = title || i18n.t('core:somethingWentWrong');
+ const isDev = process.env.NODE_ENV !== 'production';
+ return (
+ <Box sx={{ padding: 2 }} data-tid="errorBoundaryTID">
+ <Alert severity="error">
+ <Typography variant="subtitle1" sx={{ fontWeight: 'bold' }}>
+ {heading}
+ </Typography>
+ <Typography variant="body2">{message}</Typography>
+ {label && (
+ <Typography variant="caption" sx={{ display: 'block', marginTop: 1 }}>
+ {label}
+ </Typography>
+ )}
+ {isDev && (error?.stack || info?.componentStack) && (
+ <Box component="details" sx={{ marginTop: 1 }}>
+ <Box component="summary" sx={{ cursor: 'pointer' }}>
+ {i18n.t('core:showErrorDetails')}
+ </Box>
+ <Box
+ component="pre"
+ sx={{
+ whiteSpace: 'pre-wrap',
+ fontSize: 11,
+ marginTop: 1,
+ maxHeight: 240,
+ overflow: 'auto',
+ }}
+ >
+ {error?.stack}
+ {info?.componentStack}
+ </Box>
+ </Box>
+ )}
+ </Alert>
+ </Box>
+ );
+}
+
+export default ErrorBoundary;
diff --git a/src/renderer/components/RenderPerspective.tsx b/src/renderer/components/RenderPerspective.tsx
index 6024f227d..38c87bcd8 100644
--- a/src/renderer/components/RenderPerspective.tsx
+++ b/src/renderer/components/RenderPerspective.tsx
@@ -21,6 +21,7 @@ import React, { useEffect } from 'react';
import AppConfig from '-/AppConfig';
import CustomDragLayer from '-/components/CustomDragLayer';
+import { ErrorBoundary } from '-/components/ErrorBoundary';
import LoadingLazy from '-/components/LoadingLazy';
import TargetFileBox from '-/components/TargetFileBox';
import { usePerspectiveOnboardingContext } from '-/components/dialogs/hooks/usePerspectiveOnboardingContext';
@@ -29,6 +30,7 @@ import { PerspectiveSettingsContextProvider } from '-/hooks/PerspectiveSettingsC
import { ThumbGenerationContextProvider } from '-/hooks/ThumbGenerationContextProvider';
import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';
import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';
+import { useNotificationContext } from '-/hooks/useNotificationContext';
import {
AvailablePerspectives,
hasExternalPerspectiveComponent,
@@ -36,10 +38,10 @@ import {
PerspectiveIDs,
perspectiveHasOnboarding,
} from '-/perspectives';
-import PerspectiveErrorBoundary from '-/perspectives/PerspectiveErrorBoundary';
import { SortedDirContextProvider } from '-/perspectives/grid/hooks/SortedDirContextProvider';
import { Pro } from '-/pro';
import { getSeenPerspectiveOnboardings } from '-/reducers/settings';
+import i18n from '-/services/i18n';
import { NativeTypes } from 'react-dnd-html5-backend';
import { useSelector } from 'react-redux';
@@ -195,23 +197,51 @@ function ExternalPerspectiveAsync({
}) {
const Comp = getExternalPerspectiveLazy(perspectiveId);
if (!Comp) return null;
- // Error boundary isolates failures in package-shipped code (chunk-load
- // errors, render-time exceptions in the perspective module) so a crash
- // shows an inline error instead of taking down the directory pane.
return (
- <PerspectiveErrorBoundary perspectiveId={perspectiveId} context="render">
- <React.Suspense fallback={<LoadingLazy />}>
- <PerspectiveSettingsContextProvider>
- <SortedDirContextProvider>
- <PaginationContextProvider>
- <ThumbGenerationContextProvider>
- <Comp />
- </ThumbGenerationContextProvider>
- </PaginationContextProvider>
- </SortedDirContextProvider>
- </PerspectiveSettingsContextProvider>
- </React.Suspense>
- </PerspectiveErrorBoundary>
+ <React.Suspense fallback={<LoadingLazy />}>
+ <PerspectiveSettingsContextProvider>
+ <SortedDirContextProvider>
+ <PaginationContextProvider>
+ <ThumbGenerationContextProvider>
+ <Comp />
+ </ThumbGenerationContextProvider>
+ </PaginationContextProvider>
+ </SortedDirContextProvider>
+ </PerspectiveSettingsContextProvider>
+ </React.Suspense>
+ );
+}
+
+// Isolates failures in any individual perspective (built-in or external)
+// so a crash shows an inline error inside the directory pane instead of
+// blanking the whole renderer. resetKeys clears the error automatically
+// when the user switches perspective or folder.
+function PerspectiveBoundary({
+ perspectiveId,
+ currentDirectoryPath,
+ children,
+}: {
+ perspectiveId: string;
+ currentDirectoryPath?: string;
+ children: React.ReactNode;
+}) {
+ const { showNotification } = useNotificationContext();
+ return (
+ <ErrorBoundary
+ title={i18n.t('core:perspectiveFailedToLoad')}
+ label={`${i18n.t('core:perspectiveLabel')} ${perspectiveId}`}
+ resetKeys={[perspectiveId, currentDirectoryPath]}
+ onError={() =>
+ showNotification(
+ i18n.t('core:perspectiveFailedToLoad'),
+ 'error',
+ true,
+ 'perspectiveCrashTID',
+ )
+ }
+ >
+ {children}
+ </ErrorBoundary>
);
}
@@ -230,7 +260,8 @@ interface Props {}
function RenderPerspective(props: Props) {
const { currentLocationId } = useCurrentLocationContext();
- const { currentPerspective } = useDirectoryContentContext();
+ const { currentPerspective, currentDirectory } = useDirectoryContentContext();
+ const currentDirectoryPath = currentDirectory?.path;
const { openPerspectiveOnboarding } = usePerspectiveOnboardingContext();
const seenOnboardings = useSelector(getSeenPerspectiveOnboardings);
@@ -253,23 +284,31 @@ function RenderPerspective(props: Props) {
const showWelcomePanel = !currentLocationId;
function getPerspectiveComponent() {
+ const wrap = (id: string, node: React.ReactNode) => (
+ <PerspectiveBoundary
+ perspectiveId={id}
+ currentDirectoryPath={currentDirectoryPath}
+ >
+ {node}
+ </PerspectiveBoundary>
+ );
if (currentPerspective === PerspectiveIDs.LIST) {
- return <ListPerspectiveAsync />;
+ return wrap(PerspectiveIDs.LIST, <ListPerspectiveAsync />);
}
if (Pro && currentPerspective === PerspectiveIDs.GALLERY) {
- return <GalleryPerspectiveAsync />;
+ return wrap(PerspectiveIDs.GALLERY, <GalleryPerspectiveAsync />);
}
if (Pro && currentPerspective === PerspectiveIDs.MAPIQUE) {
- return <MapiquePerspectiveAsync />;
+ return wrap(PerspectiveIDs.MAPIQUE, <MapiquePerspectiveAsync />);
}
if (Pro && currentPerspective === PerspectiveIDs.KANBAN) {
- return <KanBanPerspectiveAsync />;
+ return wrap(PerspectiveIDs.KANBAN, <KanBanPerspectiveAsync />);
}
if (Pro && currentPerspective === PerspectiveIDs.FOLDERVIZ) {
- return <FolderVizPerspectiveAsync />;
+ return wrap(PerspectiveIDs.FOLDERVIZ, <FolderVizPerspectiveAsync />);
}
if (Pro && currentPerspective === PerspectiveIDs.CALENDAR) {
- return <CalendarPerspectiveAsync />;
+ return wrap(PerspectiveIDs.CALENDAR, <CalendarPerspectiveAsync />);
}
// External perspective from a package — resolved via the build-time
// generated loader map. Returns null silently if the perspective ID
@@ -279,9 +318,12 @@ function RenderPerspective(props: Props) {
(p) => p.external && p.id === currentPerspective,
);
if (externalMeta) {
- return <ExternalPerspectiveAsync perspectiveId={externalMeta.id} />;
+ return wrap(
+ externalMeta.id,
+ <ExternalPerspectiveAsync perspectiveId={externalMeta.id} />,
+ );
}
- return <GridPerspectiveAsync />;
+ return wrap(PerspectiveIDs.GRID, <GridPerspectiveAsync />);
}
if (showWelcomePanel) {
diff --git a/src/renderer/components/dialogs/hooks/PerspectiveOnboardingContextProvider.tsx b/src/renderer/components/dialogs/hooks/PerspectiveOnboardingContextProvider.tsx
index 3742c95b8..1ee6b175a 100644
--- a/src/renderer/components/dialogs/hooks/PerspectiveOnboardingContextProvider.tsx
+++ b/src/renderer/components/dialogs/hooks/PerspectiveOnboardingContextProvider.tsx
@@ -16,6 +16,7 @@
*
*/
+import { ErrorBoundary } from '-/components/ErrorBoundary';
import LoadingLazy from '-/components/LoadingLazy';
import TsDialogTitle from '-/components/dialogs/components/TsDialogTitle';
import {
@@ -23,7 +24,7 @@ import {
loadExternalPerspectiveOnboarding,
perspectiveHasOnboarding,
} from '-/perspectives';
-import PerspectiveErrorBoundary from '-/perspectives/PerspectiveErrorBoundary';
+import i18n from '-/services/i18n';
import { AppDispatch } from '-/reducers/app';
import { actions as SettingsActions } from '-/reducers/settings';
import Dialog from '@mui/material/Dialog';
@@ -124,9 +125,10 @@ export const PerspectiveOnboardingContextProvider = ({
/>
<DialogContent>
{Body && activeId && (
- <PerspectiveErrorBoundary
- perspectiveId={activeId}
- context="onboarding"
+ <ErrorBoundary
+ title={i18n.t('core:onboardingFailedToLoad')}
+ label={`${i18n.t('core:perspectiveLabel')} ${activeId}`}
+ resetKeys={[activeId]}
>
<React.Suspense fallback={<LoadingLazy />}>
{React.createElement(Body as any, {
@@ -134,7 +136,7 @@ export const PerspectiveOnboardingContextProvider = ({
perspectiveId: activeId,
})}
</React.Suspense>
- </PerspectiveErrorBoundary>
+ </ErrorBoundary>
)}
</DialogContent>
</Dialog>
diff --git a/src/renderer/containers/Root.tsx b/src/renderer/containers/Root.tsx
index 2eef9cd16..04e3cd1ef 100644
--- a/src/renderer/containers/Root.tsx
+++ b/src/renderer/containers/Root.tsx
@@ -16,7 +16,13 @@
*
*/
import AppConfig from '-/AppConfig';
+import { ErrorBoundary } from '-/components/ErrorBoundary';
import { FileUploadDialogContextProvider } from '-/components/dialogs/hooks/FileUploadDialogContextProvider';
+import i18n from '-/services/i18n';
+import Alert from '@mui/material/Alert';
+import Box from '@mui/material/Box';
+import Button from '@mui/material/Button';
+import Typography from '@mui/material/Typography';
import App from '-/containers/App';
import DialogsRoot from '-/containers/DialogsRoot';
import MainPage from '-/containers/MainPage';
@@ -62,6 +68,83 @@ type RootType = {
persistor: any;
};
+function safeT(key: string, fallback: string) {
+ try {
+ const v = i18n.t(key);
+ return typeof v === 'string' && v && v !== key ? v : fallback;
+ } catch {
+ return fallback;
+ }
+}
+
+function TopLevelFallback({ error }: { error?: Error }) {
+ const isDev = process.env.NODE_ENV !== 'production';
+ return (
+ <Box
+ sx={{
+ position: 'fixed',
+ inset: 0,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: 3,
+ }}
+ >
+ <Box
+ sx={{
+ maxWidth: 560,
+ width: '100%',
+ padding: 3,
+ border: '1px solid',
+ borderColor: 'divider',
+ borderRadius: AppConfig.defaultCSSRadius,
+ backgroundColor: 'background.paper',
+ }}
+ >
+ <Alert severity="error" sx={{ marginBottom: 2 }}>
+ <Typography variant="h6" sx={{ fontWeight: 'bold' }}>
+ {safeT('core:somethingWentWrong', 'Something went wrong')}
+ </Typography>
+ <Typography variant="body2">
+ {error?.message ||
+ safeT('core:unexpectedError', 'An unexpected error occurred')}
+ </Typography>
+ </Alert>
+ <Button
+ variant="contained"
+ color="primary"
+ onClick={() => window.location.reload()}
+ sx={{
+ borderRadius: AppConfig.defaultCSSRadius,
+ textTransform: 'none',
+ }}
+ >
+ {safeT('core:reloadApplication', 'Reload Application')}
+ </Button>
+ {isDev && error?.stack && (
+ <Box component="details" sx={{ marginTop: 2 }}>
+ <Box component="summary" sx={{ cursor: 'pointer' }}>
+ {safeT('core:showErrorDetails', 'Show error details')}
+ </Box>
+ <Box
+ component="pre"
+ sx={{
+ whiteSpace: 'pre-wrap',
+ fontSize: 11,
+ marginTop: 1,
+ maxHeight: 280,
+ overflow: 'auto',
+ }}
+ >
+ {error.stack}
+ </Box>
+ </Box>
+ )}
+ </Box>
+ </Box>
+ );
+}
+
/**
* Compose an array of providers (components that accept children) around children.
*/
@@ -183,32 +266,37 @@ export default function Root({ store, persistor }: RootType) {
}
return (
- <ReduxProvider
- // @ts-ignore
- store={store}
+ <ErrorBoundary
+ fallback={(error) => <TopLevelFallback error={error} />}
+ onError={(error, info) => console.error('Top-level crash:', error, info)}
>
- {/**
- * PersistGate delays the rendering of the app's UI until the persisted state has been retrieved
- * and saved to redux.
- * The `loading` prop can be `null` or any react instance to show during loading (e.g. a splash screen),
- * for example `loading={<SplashScreen />}`.
- * @see https://github.com/rt2zz/redux-persist/blob/master/docs/PersistGate.md
- */}
- <PersistGate
- // loading={<LoadingScreen />}
- onBeforeLift={() => {
- // eslint-disable-next-line react/prop-types
- if (!AppConfig.ExtIsAmplify) {
- // || store.app.user !== undefined
- // @ts-ignore
- store.dispatch(AppActions.initApp());
- }
- }}
+ <ReduxProvider
// @ts-ignore
- persistor={persistor}
+ store={store}
>
- {appContent}
- </PersistGate>
- </ReduxProvider>
+ {/**
+ * PersistGate delays the rendering of the app's UI until the persisted state has been retrieved
+ * and saved to redux.
+ * The `loading` prop can be `null` or any react instance to show during loading (e.g. a splash screen),
+ * for example `loading={<SplashScreen />}`.
+ * @see https://github.com/rt2zz/redux-persist/blob/master/docs/PersistGate.md
+ */}
+ <PersistGate
+ // loading={<LoadingScreen />}
+ onBeforeLift={() => {
+ // eslint-disable-next-line react/prop-types
+ if (!AppConfig.ExtIsAmplify) {
+ // || store.app.user !== undefined
+ // @ts-ignore
+ store.dispatch(AppActions.initApp());
+ }
+ }}
+ // @ts-ignore
+ persistor={persistor}
+ >
+ {appContent}
+ </PersistGate>
+ </ReduxProvider>
+ </ErrorBoundary>
);
}
diff --git a/src/renderer/hooks/NotificationContextProvider.tsx b/src/renderer/hooks/NotificationContextProvider.tsx
index 6eaaddd10..ded0e6c4a 100644
--- a/src/renderer/hooks/NotificationContextProvider.tsx
+++ b/src/renderer/hooks/NotificationContextProvider.tsx
@@ -16,8 +16,15 @@
*
*/
-import React, { createContext, useMemo, useRef, useState } from 'react';
+import React, {
+ createContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
import ConfirmDialog from '-/components/dialogs/ConfirmDialog';
+import { setGlobalErrorNotifier } from '-/services/globalErrorHandlers';
type NotificationStatus = {
visible: boolean;
@@ -140,6 +147,19 @@ export const NotificationContextProvider = ({
});
}
+ useEffect(() => {
+ setGlobalErrorNotifier((text, notificationType, autohide, tid) => {
+ setNotificationStatus({
+ visible: true,
+ text,
+ tid: tid ?? 'globalErrorTID',
+ notificationType: notificationType ?? 'error',
+ autohide: autohide ?? true,
+ });
+ });
+ return () => setGlobalErrorNotifier(null);
+ }, []);
+
function hideNotifications(excludeTypes = []) {
if (
!excludeTypes.some((type) => type === notificationStatus.notificationType)
diff --git a/src/renderer/index.tsx b/src/renderer/index.tsx
index fe36cde9a..88b1efb56 100644
--- a/src/renderer/index.tsx
+++ b/src/renderer/index.tsx
@@ -19,8 +19,11 @@
import { createRoot } from 'react-dom/client';
// import Root from './containers/Root';
import configureStore from './store/configureStore';
+import { installGlobalErrorHandlers } from './services/globalErrorHandlers';
import './app.global.css';
+installGlobalErrorHandlers();
+
const { store, persistor } = configureStore({});
document.addEventListener('contextmenu', (event) => event.preventDefault());
diff --git a/src/renderer/locales/en/core.json b/src/renderer/locales/en/core.json
index b72a5e014..1885d2f58 100644
--- a/src/renderer/locales/en/core.json
+++ b/src/renderer/locales/en/core.json
@@ -1046,6 +1046,11 @@
"onboardingFailedToLoad": "Onboarding failed to load",
"perspectiveFailedToLoad": "Perspective failed to load",
"perspectiveLabel": "Perspective:",
+ "somethingWentWrong": "Something went wrong",
+ "unexpectedError": "An unexpected error occurred",
+ "tryAgain": "Try again",
+ "showErrorDetails": "Show error details",
+ "copyErrorDetails": "Copy error details",
"entriesSelected": "{{count}} entries selected",
"foldersAndFilesFound": "{{folders}} folder(s) and {{files}} file(s) found",
"filesFound": "{{files}} file(s) found",
diff --git a/src/renderer/perspectives/PerspectiveErrorBoundary.tsx b/src/renderer/perspectives/PerspectiveErrorBoundary.tsx
deleted file mode 100644
index 03865c5ef..000000000
--- a/src/renderer/perspectives/PerspectiveErrorBoundary.tsx
+++ /dev/null
@@ -1,78 +0,0 @@
-/**
- * TagSpaces - universal file and folder organizer
- * Copyright (C) 2026-present TagSpaces GmbH
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License (version 3) as
- * published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <https://www.gnu.org/licenses/>.
- *
- */
-
-import i18n from '-/services/i18n';
-import Alert from '@mui/material/Alert';
-import Box from '@mui/material/Box';
-import Typography from '@mui/material/Typography';
-import React from 'react';
-
-type Props = {
- perspectiveId: string;
- context: 'render' | 'onboarding';
- children: React.ReactNode;
-};
-
-type State = {
- hasError: boolean;
- error?: Error;
-};
-
-// Isolates failures from external (package-shipped) perspective code so a
-// crashing perspective component or onboarding body cannot take down the
-// host renderer. Built-in perspectives are part of the bundle and treated
-// as fully trusted; this boundary is specifically for code that ships in
-// node_modules/@tagspaces/extensions/* and node_modules/@tagspacespro/extensions/*.
-export class PerspectiveErrorBoundary extends React.Component<Props, State> {
- state: State = { hasError: false };
-
- static getDerivedStateFromError(error: Error): State {
- return { hasError: true, error };
- }
-
- componentDidCatch(error: Error, info: React.ErrorInfo) {
- console.error(
- `Perspective "${this.props.perspectiveId}" (${this.props.context}) failed:`,
- error,
- info,
- );
- }
-
- render() {
- if (!this.state.hasError) return this.props.children;
- const message =
- this.state.error?.message || 'Unknown error while rendering perspective.';
- return (
- <Box sx={{ padding: 2 }} data-tid="perspectiveErrorBoundaryTID">
- <Alert severity="error">
- <Typography variant="subtitle1" sx={{ fontWeight: 'bold' }}>
- {this.props.context === 'onboarding'
- ? i18n.t('core:onboardingFailedToLoad')
- : i18n.t('core:perspectiveFailedToLoad')}
- </Typography>
- <Typography variant="body2">{message}</Typography>
- <Typography variant="caption" sx={{ display: 'block', marginTop: 1 }}>
- {i18n.t('core:perspectiveLabel')} {this.props.perspectiveId}
- </Typography>
- </Alert>
- </Box>
- );
- }
-}
-
-export default PerspectiveErrorBoundary;
diff --git a/src/renderer/services/globalErrorHandlers.ts b/src/renderer/services/globalErrorHandlers.ts
new file mode 100644
index 000000000..da8f5e60a
--- /dev/null
+++ b/src/renderer/services/globalErrorHandlers.ts
@@ -0,0 +1,92 @@
+/**
+ * TagSpaces - universal file and folder organizer
+ * Copyright (C) 2026-present TagSpaces GmbH
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License (version 3) as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+type Notifier = (
+ text: string,
+ notificationType?: 'default' | 'info' | 'warning' | 'error',
+ autohide?: boolean,
+ tid?: string,
+) => void;
+
+let currentNotifier: Notifier | null = null;
+let installed = false;
+let errorListener: ((event: ErrorEvent) => void) | null = null;
+let rejectionListener: ((event: PromiseRejectionEvent) => void) | null = null;
+
+export function setGlobalErrorNotifier(fn: Notifier | null) {
+ currentNotifier = fn;
+}
+
+function notify(message: string) {
+ if (currentNotifier) {
+ try {
+ currentNotifier(message, 'error', true, 'globalErrorTID');
+ } catch (e) {
+ console.error('globalErrorHandlers: notifier threw', e);
+ }
+ }
+}
+
+function fallbackMessage() {
+ try {
+ // Resolve lazily so this module has no eager dependency on i18n.
+ // eslint-disable-next-line @typescript-eslint/no-var-requires, global-require
+ const i18n = require('-/services/i18n').default;
+ return i18n.t('core:unexpectedError');
+ } catch {
+ return 'An unexpected error occurred';
+ }
+}
+
+export function installGlobalErrorHandlers() {
+ if (installed || typeof window === 'undefined') return;
+ installed = true;
+
+ errorListener = (event: ErrorEvent) => {
+ // Resource-load failures (img/script/link) deliver ErrorEvent with no
+ // `error` field. They are noisy and not actionable here.
+ if (!event.error) return;
+ console.error('window.onerror:', event.error);
+ notify(event.error?.message || fallbackMessage());
+ };
+
+ rejectionListener = (event: PromiseRejectionEvent) => {
+ const reason: any = event.reason;
+ console.error('unhandledrejection:', reason);
+ const msg =
+ reason instanceof Error
+ ? reason.message
+ : typeof reason === 'string'
+ ? reason
+ : fallbackMessage();
+ notify(msg);
+ };
+
+ window.addEventListener('error', errorListener);
+ window.addEventListener('unhandledrejection', rejectionListener);
+}
+
+export function uninstallGlobalErrorHandlers() {
+ if (!installed || typeof window === 'undefined') return;
+ if (errorListener) window.removeEventListener('error', errorListener);
+ if (rejectionListener)
+ window.removeEventListener('unhandledrejection', rejectionListener);
+ errorListener = null;
+ rejectionListener = null;
+ installed = false;
+}