diff --git a/app/actions/definitions/collections.tsx b/app/actions/definitions/collections.tsx index 4dca402f7a..08729e4bda 100644 --- a/app/actions/definitions/collections.tsx +++ b/app/actions/definitions/collections.tsx @@ -20,6 +20,7 @@ import { UnsubscribeIcon, } from "outline-icons"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import Collection from "~/models/Collection"; import { CollectionEdit } from "~/components/Collection/CollectionEdit"; import { CollectionNew } from "~/components/Collection/CollectionNew"; @@ -173,7 +174,7 @@ export const importDocument = createAction({ }); history.push(document.path); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { toast.dismiss(toastId); } diff --git a/app/actions/definitions/documents.tsx b/app/actions/definitions/documents.tsx index 0c2e18517b..6efba6eaa5 100644 --- a/app/actions/definitions/documents.tsx +++ b/app/actions/definitions/documents.tsx @@ -36,6 +36,7 @@ import { OpenIcon, } from "outline-icons"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import Icon from "@shared/components/Icon"; import type { NavigationNode } from "@shared/types"; import { ExportContentType, TeamPreference } from "@shared/types"; @@ -1123,7 +1124,7 @@ export const importDocument = createAction({ ); history.push(document.url); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { toast.dismiss(toastId); } diff --git a/app/actions/definitions/shares.tsx b/app/actions/definitions/shares.tsx index 5ddde114e3..fb4ce8239a 100644 --- a/app/actions/definitions/shares.tsx +++ b/app/actions/definitions/shares.tsx @@ -1,4 +1,5 @@ import copy from "copy-to-clipboard"; +import { errToString } from "@shared/utils/error"; import type Share from "~/models/Share"; import { createAction, createInternalLinkAction } from ".."; import { ArrowIcon, CopyIcon, TrashIcon } from "outline-icons"; @@ -53,7 +54,7 @@ export const revokeShareFactory = ({ await stores.shares.revoke(share); toast.message(t("Share link revoked")); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, }); diff --git a/app/components/Collection/CollectionEdit.tsx b/app/components/Collection/CollectionEdit.tsx index cef1e0c80b..c85e94c9dc 100644 --- a/app/components/Collection/CollectionEdit.tsx +++ b/app/components/Collection/CollectionEdit.tsx @@ -1,6 +1,7 @@ import { observer } from "mobx-react"; import { useCallback } from "react"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import useStores from "~/hooks/useStores"; import type { FormData } from "./CollectionForm"; import { CollectionForm } from "./CollectionForm"; @@ -23,7 +24,7 @@ export const CollectionEdit = observer(function CollectionEdit_({ await collection?.save(data); onSubmit?.(); } catch (error) { - toast.error(error.message); + toast.error(errToString(error)); } }, [collection, onSubmit] diff --git a/app/components/Collection/CollectionNew.tsx b/app/components/Collection/CollectionNew.tsx index 05877b2c03..1645f93f5f 100644 --- a/app/components/Collection/CollectionNew.tsx +++ b/app/components/Collection/CollectionNew.tsx @@ -2,6 +2,7 @@ import { runInAction } from "mobx"; import { observer } from "mobx-react"; import { useCallback } from "react"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import useStores from "~/hooks/useStores"; import history from "~/utils/history"; import type { FormData } from "./CollectionForm"; @@ -26,7 +27,7 @@ export const CollectionNew = observer(function CollectionNew_({ onSubmit?.(); history.push(collection.path); } catch (error) { - toast.error(error.message); + toast.error(errToString(error)); } }, [collections, onSubmit] diff --git a/app/components/CommentDeleteDialog.tsx b/app/components/CommentDeleteDialog.tsx index 7808c022b4..61c8faa899 100644 --- a/app/components/CommentDeleteDialog.tsx +++ b/app/components/CommentDeleteDialog.tsx @@ -1,6 +1,7 @@ import { observer } from "mobx-react"; import { useTranslation, Trans } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import type Comment from "~/models/Comment"; import ConfirmationDialog from "~/components/ConfirmationDialog"; import Text from "~/components/Text"; @@ -21,7 +22,7 @@ function CommentDeleteDialog({ comment, onSubmit }: Props) { await comment.delete(); onSubmit?.(); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }; diff --git a/app/components/ConfirmMoveDialog.tsx b/app/components/ConfirmMoveDialog.tsx index 75d13f186a..55401670a8 100644 --- a/app/components/ConfirmMoveDialog.tsx +++ b/app/components/ConfirmMoveDialog.tsx @@ -1,6 +1,7 @@ import { observer } from "mobx-react"; import { Trans, useTranslation } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import type { NavigationNode } from "@shared/types"; import { CollectionPermission } from "@shared/types"; import type Collection from "~/models/Collection"; @@ -50,7 +51,7 @@ function ConfirmMoveDialog({ collection, item, ...rest }: Props) { ) ); } else { - toast.error(err.message); + toast.error(errToString(err)); } } finally { dialogs.closeAllModals(); diff --git a/app/components/ConfirmationDialog.tsx b/app/components/ConfirmationDialog.tsx index 6dc927d312..75e702f9d9 100644 --- a/app/components/ConfirmationDialog.tsx +++ b/app/components/ConfirmationDialog.tsx @@ -2,6 +2,7 @@ import { observer } from "mobx-react"; import * as React from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import Button from "~/components/Button"; import Flex from "~/components/Flex"; import Text from "~/components/Text"; @@ -44,7 +45,7 @@ const ConfirmationDialog: React.FC = ({ } dialogs.closeAllModals(); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { setIsSaving(false); } diff --git a/app/components/DefaultCollectionInputSelect.tsx b/app/components/DefaultCollectionInputSelect.tsx index e46edac00a..caac5675eb 100644 --- a/app/components/DefaultCollectionInputSelect.tsx +++ b/app/components/DefaultCollectionInputSelect.tsx @@ -8,6 +8,7 @@ import { getLuminance } from "polished"; import React, { useState } from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; +import { toError } from "@shared/utils/error"; import Icon from "@shared/components/Icon"; import { colorPalette } from "@shared/utils/collections"; import type { Option } from "~/components/InputSelect"; @@ -27,7 +28,7 @@ const DefaultCollectionInputSelect = observer( const { t } = useTranslation(); const { collections, ui } = useStores(); const [fetching, setFetching] = useState(false); - const [fetchError, setFetchError] = useState(); + const [fetchError, setFetchError] = useState(); React.useEffect(() => { async function fetchData() { @@ -41,7 +42,7 @@ const DefaultCollectionInputSelect = observer( toast.error( t("Collections could not be loaded, please reload the app") ); - setFetchError(error); + setFetchError(toError(error)); } finally { setFetching(false); } diff --git a/app/components/EditableTitle.tsx b/app/components/EditableTitle.tsx index 38f0433e3b..cd9b065e0a 100644 --- a/app/components/EditableTitle.tsx +++ b/app/components/EditableTitle.tsx @@ -1,6 +1,7 @@ import * as React from "react"; import { toast } from "sonner"; import styled from "styled-components"; +import { errToString } from "@shared/utils/error"; import { s, ellipsis } from "@shared/styles"; import EventBoundary from "@shared/components/EventBoundary"; @@ -109,7 +110,7 @@ function EditableTitle( setValue(value); setIsEditing(true); - toast.error(error.message); + toast.error(errToString(error)); throw error; } finally { setIsSubmitting(false); diff --git a/app/components/OAuthClient/OAuthClientNew.tsx b/app/components/OAuthClient/OAuthClientNew.tsx index 3b364bce63..6337874f3b 100644 --- a/app/components/OAuthClient/OAuthClientNew.tsx +++ b/app/components/OAuthClient/OAuthClientNew.tsx @@ -2,6 +2,7 @@ import { observer } from "mobx-react"; import { useCallback } from "react"; import { useHistory } from "react-router-dom"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import useStores from "~/hooks/useStores"; import { settingsPath } from "~/utils/routeHelpers"; import type { FormData } from "./OAuthClientForm"; @@ -24,7 +25,7 @@ export const OAuthClientNew = observer(function OAuthClientNew_({ onSubmit?.(); history.push(settingsPath("applications", oauthClient.id)); } catch (error) { - toast.error(error.message); + toast.error(errToString(error)); } }, [oauthClients, history, onSubmit] diff --git a/app/components/PaginatedList.tsx b/app/components/PaginatedList.tsx index 914957159b..084e7665c7 100644 --- a/app/components/PaginatedList.tsx +++ b/app/components/PaginatedList.tsx @@ -2,6 +2,7 @@ import { isEqual } from "es-toolkit/compat"; import * as React from "react"; import { useTranslation } from "react-i18next"; import { Waypoint } from "react-waypoint"; +import { toError } from "@shared/utils/error"; import { Pagination } from "@shared/constants"; import ArrowKeyNavigation from "~/components/ArrowKeyNavigation"; import DelayedMount from "~/components/DelayedMount"; @@ -176,7 +177,7 @@ const PaginatedList = ({ setIsFetchingInitial(false); } catch (err) { - setError(err); + setError(toError(err)); } finally { // only the most recent fetch should end the loading state if (counter >= fetchCounter) { diff --git a/app/components/Sharing/Collection/AccessControlList.tsx b/app/components/Sharing/Collection/AccessControlList.tsx index 0207d58f23..d7c82e3c3e 100644 --- a/app/components/Sharing/Collection/AccessControlList.tsx +++ b/app/components/Sharing/Collection/AccessControlList.tsx @@ -4,6 +4,7 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import styled, { useTheme } from "styled-components"; +import { errToString } from "@shared/utils/error"; import Squircle from "@shared/components/Squircle"; import { s } from "@shared/styles"; import { CollectionPermission } from "@shared/types"; @@ -186,7 +187,7 @@ export const AccessControlList = observer( }); } } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); return false; } return true; @@ -240,7 +241,7 @@ export const AccessControlList = observer( }); } } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); return false; } return true; diff --git a/app/components/Sharing/Collection/PublicAccess.tsx b/app/components/Sharing/Collection/PublicAccess.tsx index e11cc00687..fcf2ffad50 100644 --- a/app/components/Sharing/Collection/PublicAccess.tsx +++ b/app/components/Sharing/Collection/PublicAccess.tsx @@ -6,6 +6,7 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import { useTheme } from "styled-components"; +import { errToString } from "@shared/utils/error"; import Squircle from "@shared/components/Squircle"; import { UrlHelper } from "@shared/utils/UrlHelper"; import type Collection from "~/models/Collection"; @@ -71,7 +72,7 @@ function InnerPublicAccess( } } } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { setCreating(false); } @@ -100,7 +101,8 @@ function InnerPublicAccess( urlId: isEmpty(val) ? null : val, }); } catch (err) { - if (err.message.includes("must be unique")) { + const message = errToString(err); + if (message.includes("must be unique")) { setValidationError(t("Sorry, this link has already been used")); } } diff --git a/app/components/Sharing/Document/PublicAccess.tsx b/app/components/Sharing/Document/PublicAccess.tsx index 86a423c611..e57a2fd3e9 100644 --- a/app/components/Sharing/Document/PublicAccess.tsx +++ b/app/components/Sharing/Document/PublicAccess.tsx @@ -6,6 +6,7 @@ import * as React from "react"; import { Trans, useTranslation } from "react-i18next"; import { toast } from "sonner"; import { useTheme } from "styled-components"; +import { errToString } from "@shared/utils/error"; import Flex from "@shared/components/Flex"; import Squircle from "@shared/components/Squircle"; import { UrlHelper } from "@shared/utils/UrlHelper"; @@ -81,7 +82,7 @@ function PublicAccess( } } } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { setCreating(false); } @@ -110,7 +111,8 @@ function PublicAccess( urlId: isEmpty(val) ? null : val, }); } catch (err) { - if (err.message.includes("must be unique")) { + const message = errToString(err); + if (message.includes("must be unique")) { setValidationError(t("Sorry, this link has already been used")); } } diff --git a/app/components/Sharing/components/ShareSettingsPopover.tsx b/app/components/Sharing/components/ShareSettingsPopover.tsx index 2c0bf7309d..964e797da1 100644 --- a/app/components/Sharing/components/ShareSettingsPopover.tsx +++ b/app/components/Sharing/components/ShareSettingsPopover.tsx @@ -10,6 +10,7 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import styled, { useTheme } from "styled-components"; +import { errToString } from "@shared/utils/error"; import { s } from "@shared/styles"; import { HStack } from "~/components/primitives/HStack"; import { AttachmentPreset } from "@shared/types"; @@ -70,7 +71,7 @@ function ShareSettingsPopover({ share, children }: Props) { await share.save({ title: val || null }); hasChangesRef.current = true; } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, 500), [share] @@ -100,7 +101,7 @@ function ShareSettingsPopover({ share, children }: Props) { await share.save({ iconUrl: attachment.url }); hasChangesRef.current = true; } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { setIsUploading(false); if (fileInputRef.current) { @@ -116,7 +117,7 @@ function ShareSettingsPopover({ share, children }: Props) { await share.save({ iconUrl: null }); hasChangesRef.current = true; } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, [share]); @@ -126,7 +127,7 @@ function ShareSettingsPopover({ share, children }: Props) { await share.save({ allowIndexing: checked }); hasChangesRef.current = true; } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, [share] @@ -138,7 +139,7 @@ function ShareSettingsPopover({ share, children }: Props) { await share.save({ allowSubscriptions: checked }); hasChangesRef.current = true; } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, [share] @@ -150,7 +151,7 @@ function ShareSettingsPopover({ share, children }: Props) { await share.save({ showLastUpdated: checked }); hasChangesRef.current = true; } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, [share] @@ -162,7 +163,7 @@ function ShareSettingsPopover({ share, children }: Props) { await share.save({ showTOC: checked }); hasChangesRef.current = true; } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, [share] diff --git a/app/components/Sidebar/components/Version.tsx b/app/components/Sidebar/components/Version.tsx index 66f9a8affd..1a8066b149 100644 --- a/app/components/Sidebar/components/Version.tsx +++ b/app/components/Sidebar/components/Version.tsx @@ -1,6 +1,7 @@ import { useState, useEffect } from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; +import { toError } from "@shared/utils/error"; import Badge from "~/components/Badge"; import { client } from "~/utils/ApiClient"; import Logger from "~/utils/Logger"; @@ -20,7 +21,7 @@ export default function Version() { setVersionsBehind(res.data.versionsBehind); } } catch (error) { - Logger.error("Failed to load version info", error); + Logger.error("Failed to load version info", toError(error)); } } diff --git a/app/components/Sidebar/hooks/useDragAndDrop.tsx b/app/components/Sidebar/hooks/useDragAndDrop.tsx index 88e2896c16..83d9f926b6 100644 --- a/app/components/Sidebar/hooks/useDragAndDrop.tsx +++ b/app/components/Sidebar/hooks/useDragAndDrop.tsx @@ -5,6 +5,7 @@ import { useDrag, useDrop } from "react-dnd"; import { getEmptyImage } from "react-dnd-html5-backend"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import Icon from "@shared/components/Icon"; import type { NavigationNode } from "@shared/types"; import type Collection from "~/models/Collection"; @@ -275,7 +276,7 @@ export function useDropToChangeCollection( ) ); } else { - toast.error(err.message); + toast.error(errToString(err)); } } } @@ -370,7 +371,7 @@ export function useDropToReparentDocument( ) ); } else { - toast.error(err.message); + toast.error(errToString(err)); } } } @@ -483,7 +484,7 @@ export function useDropToReorderDocument( }) ); } else { - toast.error(err.message); + toast.error(errToString(err)); } } } @@ -620,7 +621,7 @@ export function useDropToUnpublish() { }) ); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, canDrop: (item) => { diff --git a/app/components/UserDialogs.tsx b/app/components/UserDialogs.tsx index a6ce379f31..2d06a55f6f 100644 --- a/app/components/UserDialogs.tsx +++ b/app/components/UserDialogs.tsx @@ -2,6 +2,7 @@ import { observer } from "mobx-react"; import * as React from "react"; import { Trans, useTranslation } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import { UserRole } from "@shared/types"; import { UserValidation } from "@shared/validations"; import type User from "~/models/User"; @@ -157,7 +158,7 @@ export const UserChangeAvatarDialog = observer(function UserChangeAvatarDialog({ await user.save({ avatarUrl }); toast.success(t("Profile picture updated")); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }; @@ -205,7 +206,7 @@ export function UserChangeEmailDialog({ user, onSubmit }: Props) { ); return true; } catch (err) { - setError(err.message); + setError(errToString(err)); return false; } }; diff --git a/app/components/WebsocketProvider.tsx b/app/components/WebsocketProvider.tsx index 62c19d4bda..17009e790e 100644 --- a/app/components/WebsocketProvider.tsx +++ b/app/components/WebsocketProvider.tsx @@ -13,6 +13,7 @@ import { FileOperationType, ImportState, } from "@shared/types"; +import { toError } from "@shared/utils/error"; import type RootStore from "~/stores/RootStore"; import type Collection from "~/models/Collection"; import type Comment from "~/models/Comment"; @@ -340,7 +341,7 @@ function useDocumentHandlers() { force: event.userId === currentUserId, }); } catch (err) { - Logger.error("Failed to fetch document after add_user", err); + Logger.error("Failed to fetch document after add_user", toError(err)); } } ); @@ -439,7 +440,10 @@ function useCollectionHandlers() { try { await collections.fetch(collectionId, { force: true }); } catch (err) { - Logger.error("Failed to fetch collection after archive", err); + Logger.error( + "Failed to fetch collection after archive", + toError(err) + ); } documents.unarchivedInCollection(collectionId).forEach( @@ -475,7 +479,10 @@ function useCollectionHandlers() { try { await collections.fetch(collectionId, { force: true }); } catch (err) { - Logger.error("Failed to fetch collection after restore", err); + Logger.error( + "Failed to fetch collection after restore", + toError(err) + ); } } ); @@ -487,7 +494,7 @@ function useCollectionHandlers() { force: event.userId === currentUserId, }); } catch (err) { - Logger.error("Failed to fetch collection after add_user", err); + Logger.error("Failed to fetch collection after add_user", toError(err)); } }); @@ -505,7 +512,10 @@ function useCollectionHandlers() { try { await collections.fetch(event.collectionId!); } catch (err) { - Logger.error("Failed to fetch collection after add_group", err); + Logger.error( + "Failed to fetch collection after add_group", + toError(err) + ); } }); @@ -637,7 +647,10 @@ function useUserHandlers() { try { await collections.fetchAll(); } catch (err) { - Logger.error("Failed to fetch collections after demote", err); + Logger.error( + "Failed to fetch collections after demote", + toError(err) + ); } } }); diff --git a/app/editor/components/FloatingToolbar.tsx b/app/editor/components/FloatingToolbar.tsx index 73f5ea412f..73f8f31c25 100644 --- a/app/editor/components/FloatingToolbar.tsx +++ b/app/editor/components/FloatingToolbar.tsx @@ -68,7 +68,7 @@ function usePosition({ fromPos = view.coordsAtPos(selection.from); toPos = view.coordsAtPos(selection.to, -1); } catch (err) { - Logger.warn("Unable to calculate selection position", err); + Logger.warn("Unable to calculate selection position", { err }); return defaultPosition; } diff --git a/app/editor/components/SuggestionsMenu.tsx b/app/editor/components/SuggestionsMenu.tsx index d1a497f7e1..e2df81a4c4 100644 --- a/app/editor/components/SuggestionsMenu.tsx +++ b/app/editor/components/SuggestionsMenu.tsx @@ -108,7 +108,7 @@ function SuggestionsMenu(props: Props) { const right = Math.max(fromPos.right, toPos.right); return new DOMRect(left, top, right - left, bottom - top); } catch (err) { - Logger.warn("Unable to calculate caret position", err); + Logger.warn("Unable to calculate caret position", { err }); return new DOMRect(); } }, [props.isActive, view]); diff --git a/app/hooks/useEmbeds.ts b/app/hooks/useEmbeds.ts index aaaad31ddc..2c1c3ccc3c 100644 --- a/app/hooks/useEmbeds.ts +++ b/app/hooks/useEmbeds.ts @@ -1,5 +1,6 @@ import { find } from "es-toolkit/compat"; import { useEffect, useMemo } from "react"; +import { toError } from "@shared/utils/error"; import embeds from "@shared/editor/embeds"; import { IntegrationType, TeamPreference } from "@shared/types"; import type Integration from "~/models/Integration"; @@ -24,7 +25,7 @@ export default function useEmbeds(loadIfMissing = false) { type: IntegrationType.Embed, }); } catch (err) { - Logger.error("Failed to fetch embed integrations", err); + Logger.error("Failed to fetch embed integrations", toError(err)); } } diff --git a/app/hooks/useImportDocument.ts b/app/hooks/useImportDocument.ts index e07e9fbcd1..05d9eabf4e 100644 --- a/app/hooks/useImportDocument.ts +++ b/app/hooks/useImportDocument.ts @@ -3,6 +3,7 @@ import { useState, useCallback } from "react"; import { useTranslation } from "react-i18next"; import { useHistory } from "react-router-dom"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import { useSidebarContext } from "~/components/Sidebar/components/SidebarContext"; import useStores from "~/hooks/useStores"; import { documentPath } from "~/utils/routeHelpers"; @@ -61,13 +62,13 @@ export default function useImportDocument( }); } } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { toast.dismiss(toastId); } } } catch (err) { - toast.error(`${t("Could not import file")}. ${err.message}`); + toast.error(`${t("Could not import file")}. ${errToString(err)}`); } finally { setImporting(false); importingLock = false; diff --git a/app/hooks/useRequest.ts b/app/hooks/useRequest.ts index 7bfaae3244..9061c2b812 100644 --- a/app/hooks/useRequest.ts +++ b/app/hooks/useRequest.ts @@ -29,7 +29,7 @@ export default function useRequest( const [data, setData] = useState(); const [loading, setLoading] = useState(false); const [loaded, setLoaded] = useState(false); - const [error, setError] = useState(); + const [error, setError] = useState(); const request = useCallback(async () => { setLoading(true); diff --git a/app/hooks/useUserMenuActions.tsx b/app/hooks/useUserMenuActions.tsx index a976c6c21e..99637aa2c6 100644 --- a/app/hooks/useUserMenuActions.tsx +++ b/app/hooks/useUserMenuActions.tsx @@ -110,7 +110,9 @@ export function useUserMenuActions(targetUser: User | null) { toast.success(t(`Invite was resent to ${targetUser.name}`)); } catch (err) { toast.error( - err.message ?? t(`An error occurred while sending the invite`) + err instanceof Error + ? err.message + : t(`An error occurred while sending the invite`) ); } }, [users, targetUser, t]); diff --git a/app/models/base/Model.ts b/app/models/base/Model.ts index 901f116125..1598d14d35 100644 --- a/app/models/base/Model.ts +++ b/app/models/base/Model.ts @@ -153,7 +153,7 @@ export default abstract class Model { // @ts-expect-error TODO this[key] = data[key]; } catch (error) { - Logger.warn(`Error setting ${key} on model`, error); + Logger.warn(`Error setting ${key} on model`, { error }); } } diff --git a/app/models/decorators/Relation.ts b/app/models/decorators/Relation.ts index db100aa605..2f72755bd2 100644 --- a/app/models/decorators/Relation.ts +++ b/app/models/decorators/Relation.ts @@ -1,5 +1,6 @@ import invariant from "invariant"; import { singular } from "pluralize"; +import { toError } from "@shared/utils/error"; import type Model from "../base/Model"; import Logger from "~/utils/Logger"; @@ -61,7 +62,7 @@ export const getInverseRelationsForModelClass = (targetClass: typeof Model) => { } catch (error) { Logger.error( `Error resolving relation ${modelName}.${propertyName} for target ${targetClass.modelName}:`, - error + toError(error) ); } }); diff --git a/app/scenes/ApiKeyNew/index.tsx b/app/scenes/ApiKeyNew/index.tsx index 53064de406..6b1da73bee 100644 --- a/app/scenes/ApiKeyNew/index.tsx +++ b/app/scenes/ApiKeyNew/index.tsx @@ -3,6 +3,7 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import styled from "styled-components"; +import { errToString } from "@shared/utils/error"; import { ApiKeyValidation } from "@shared/validations"; import Button from "~/components/Button"; import Flex from "~/components/Flex"; @@ -85,7 +86,7 @@ function ApiKeyNew({ onSubmit }: Props) { ); onSubmit(); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { setIsSaving(false); } diff --git a/app/scenes/Collection/index.tsx b/app/scenes/Collection/index.tsx index 39f2d72554..59e80b2bcd 100644 --- a/app/scenes/Collection/index.tsx +++ b/app/scenes/Collection/index.tsx @@ -11,6 +11,7 @@ import { Redirect, } from "react-router-dom"; import styled from "styled-components"; +import { toError } from "@shared/utils/error"; import { s } from "@shared/styles"; import { StatusFilter } from "@shared/types"; import type Collection from "~/models/Collection"; @@ -109,7 +110,7 @@ const CollectionScene = observer(function CollectionScene_() { setError(undefined); await collections.fetch(id); } catch (err) { - setError(err); + setError(toError(err)); } } diff --git a/app/scenes/Document/components/DataLoader.tsx b/app/scenes/Document/components/DataLoader.tsx index c5fae17713..796266b6d7 100644 --- a/app/scenes/Document/components/DataLoader.tsx +++ b/app/scenes/Document/components/DataLoader.tsx @@ -2,6 +2,7 @@ import { observer } from "mobx-react"; import * as React from "react"; import type { RouteComponentProps, StaticContext } from "react-router"; import { Redirect, useLocation } from "react-router"; +import { toError } from "@shared/utils/error"; import { TeamPreference } from "@shared/types"; import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper"; import { RevisionHelper } from "@shared/utils/RevisionHelper"; @@ -105,7 +106,7 @@ function DataLoader({ match, children }: Props) { force: missingPolicy, }); } catch (err) { - setError(err); + setError(toError(err)); } } void fetchDocument(); @@ -152,7 +153,7 @@ function DataLoader({ match, children }: Props) { documentId: document.id, }); } catch (err) { - Logger.error("Failed to fetch views", err); + Logger.error("Failed to fetch views", toError(err)); } } } diff --git a/app/scenes/Document/hooks/useDocumentSave.ts b/app/scenes/Document/hooks/useDocumentSave.ts index 54b3f3e8a5..9c6f281af5 100644 --- a/app/scenes/Document/hooks/useDocumentSave.ts +++ b/app/scenes/Document/hooks/useDocumentSave.ts @@ -5,6 +5,7 @@ import { AllSelection, TextSelection } from "prosemirror-state"; import { useState, useRef, useEffect, useCallback, useMemo } from "react"; import { useHistory } from "react-router-dom"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper"; import { TextHelper } from "@shared/utils/TextHelper"; import type Document from "~/models/Document"; @@ -182,7 +183,7 @@ export function useDocumentSave({ ui.setActiveDocument(savedDocument); } } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { setIsSaving(false); setIsPublishing(false); @@ -341,7 +342,8 @@ export function useDocumentSave({ () => () => { autosave.cancel(); const currentDoc = editorRef.current?.view.state.doc; - const isEditorEmpty = !currentDoc || ProsemirrorHelper.isEmpty(currentDoc); + const isEditorEmpty = + !currentDoc || ProsemirrorHelper.isEmpty(currentDoc); if ( shouldAutoDeleteDraftOnUnmount({ diff --git a/app/scenes/DocumentDelete.tsx b/app/scenes/DocumentDelete.tsx index 76e370f1cc..70bc5a7afb 100644 --- a/app/scenes/DocumentDelete.tsx +++ b/app/scenes/DocumentDelete.tsx @@ -3,6 +3,7 @@ import * as React from "react"; import { useTranslation, Trans } from "react-i18next"; import { useHistory } from "react-router-dom"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import type Document from "~/models/Document"; import Button from "~/components/Button"; import Flex from "~/components/Flex"; @@ -64,7 +65,7 @@ function DocumentDelete({ document, onSubmit }: Props) { onSubmit(); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { setDeleting(false); } @@ -90,7 +91,7 @@ function DocumentDelete({ document, onSubmit }: Props) { await document.archive(); onSubmit(); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { setArchiving(false); } diff --git a/app/scenes/Errors/Error403.tsx b/app/scenes/Errors/Error403.tsx index 3143bdde9e..14402cfd32 100644 --- a/app/scenes/Errors/Error403.tsx +++ b/app/scenes/Errors/Error403.tsx @@ -2,6 +2,7 @@ import { useCallback, useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import { useHistory, useLocation } from "react-router-dom"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import Button from "~/components/Button"; import Empty from "~/components/Empty"; import Heading from "~/components/Heading"; @@ -57,7 +58,7 @@ const Error403 = ({ documentId }: Props) => { setRequested(true); toast.success(t("Access request sent")); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { setRequesting(false); } diff --git a/app/scenes/Invite.tsx b/app/scenes/Invite.tsx index b6a3885187..7c9cae0f4f 100644 --- a/app/scenes/Invite.tsx +++ b/app/scenes/Invite.tsx @@ -6,6 +6,7 @@ import { useTranslation, Trans } from "react-i18next"; import { Link } from "react-router-dom"; import { toast } from "sonner"; import styled from "styled-components"; +import { errToString } from "@shared/utils/error"; import { UserRole } from "@shared/types"; import { parseEmail } from "@shared/utils/email"; import { UserValidation } from "@shared/validations"; @@ -66,7 +67,7 @@ function Invite({ onSubmit }: Props) { toast.message(t("Those email addresses are already invited")); } } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { setIsSaving(false); } diff --git a/app/scenes/Login/components/AuthenticationProvider.tsx b/app/scenes/Login/components/AuthenticationProvider.tsx index 00ad9cf7b2..4a1c67de10 100644 --- a/app/scenes/Login/components/AuthenticationProvider.tsx +++ b/app/scenes/Login/components/AuthenticationProvider.tsx @@ -4,6 +4,7 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import styled from "styled-components"; +import { errToString } from "@shared/utils/error"; import { Client } from "@shared/types"; import ButtonLarge from "~/components/ButtonLarge"; import InputLarge from "~/components/InputLarge"; @@ -122,7 +123,7 @@ function AuthenticationProvider(props: Props) { // Submit form natively to let browser handle redirect and cookies formRef.current?.submit(); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }; diff --git a/app/scenes/Settings/Application.tsx b/app/scenes/Settings/Application.tsx index a422d62586..55db759f7c 100644 --- a/app/scenes/Settings/Application.tsx +++ b/app/scenes/Settings/Application.tsx @@ -6,6 +6,7 @@ import { useTranslation } from "react-i18next"; import { useParams } from "react-router-dom"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import { OAuthClientValidation } from "@shared/validations"; import type OAuthClient from "~/models/oauth/OAuthClient"; import Breadcrumb from "~/components/Breadcrumb"; @@ -103,7 +104,7 @@ const Application = observer(function Application({ oauthClient }: Props) { : t("Application updated") ); } catch (error) { - toast.error(error.message); + toast.error(errToString(error)); } }, [oauthClient, t] @@ -115,7 +116,7 @@ const Application = observer(function Application({ oauthClient }: Props) { await oauthClient.rotateClientSecret(); toast.success(t("Client secret rotated")); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }; diff --git a/app/scenes/Settings/Authentication.tsx b/app/scenes/Settings/Authentication.tsx index 07d92e3b41..6a48593538 100644 --- a/app/scenes/Settings/Authentication.tsx +++ b/app/scenes/Settings/Authentication.tsx @@ -3,6 +3,7 @@ import { EmailIcon, PadlockIcon } from "outline-icons"; import * as React from "react"; import { useTranslation, Trans } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import ConfirmationDialog from "~/components/ConfirmationDialog"; import Flex from "~/components/Flex"; import Heading from "~/components/Heading"; @@ -52,7 +53,7 @@ function Authentication() { await team.save({ guestSignin: checked }); toast.success(t("Settings saved")); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, [team, t] @@ -64,7 +65,7 @@ function Authentication() { await provider.save({ isEnabled }); toast.success(t("Settings saved")); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, [t] @@ -114,7 +115,7 @@ function Authentication() { }); toast.success(t("Settings saved")); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } })(); } else { @@ -143,7 +144,7 @@ function Authentication() { }); toast.success(t("Settings saved")); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, [t] @@ -308,7 +309,7 @@ function Authentication() { await team.save({ passkeysEnabled: checked }); toast.success(t("Settings saved")); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }} /> @@ -370,7 +371,7 @@ const DisableGroupSyncDialog = observer(function DisableGroupSyncDialog({ toast.success(t("Settings saved")); onSubmit(); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { setIsSaving(false); } diff --git a/app/scenes/Settings/Details.tsx b/app/scenes/Settings/Details.tsx index 39582ec556..f20499be31 100644 --- a/app/scenes/Settings/Details.tsx +++ b/app/scenes/Settings/Details.tsx @@ -7,6 +7,7 @@ import * as React from "react"; import { useTranslation, Trans } from "react-i18next"; import { toast } from "sonner"; import { ThemeProvider, useTheme } from "styled-components"; +import { errToString } from "@shared/utils/error"; import { buildDarkTheme, buildLightTheme } from "@shared/styles/theme"; import type { CustomTheme } from "@shared/types"; import { TOCPosition, TeamPreference } from "@shared/types"; @@ -110,7 +111,7 @@ function Details() { }); toast.success(t("Settings saved")); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, [ diff --git a/app/scenes/Settings/Profile.tsx b/app/scenes/Settings/Profile.tsx index 947f6801d3..4ee6b30051 100644 --- a/app/scenes/Settings/Profile.tsx +++ b/app/scenes/Settings/Profile.tsx @@ -3,6 +3,7 @@ import { ProfileIcon } from "outline-icons"; import * as React from "react"; import { Trans, useTranslation } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import Button from "~/components/Button"; import Heading from "~/components/Heading"; import Input from "~/components/Input"; @@ -30,7 +31,7 @@ const Profile = () => { await user.save({ name }); toast.success(t("Profile saved")); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }; diff --git a/app/scenes/Settings/Security.tsx b/app/scenes/Settings/Security.tsx index c38344a311..8b145f2e49 100644 --- a/app/scenes/Settings/Security.tsx +++ b/app/scenes/Settings/Security.tsx @@ -5,6 +5,7 @@ import { useState } from "react"; import * as React from "react"; import { useTranslation, Trans } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import { TeamPreference, EmailDisplay } from "@shared/types"; import ConfirmationDialog from "~/components/ConfirmationDialog"; import Heading from "~/components/Heading"; @@ -86,7 +87,7 @@ function Security() { await team.save(newData); showSuccessMessage(); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, [team, showSuccessMessage] diff --git a/app/scenes/Settings/Template.tsx b/app/scenes/Settings/Template.tsx index beb9d814b7..65b6cbf891 100644 --- a/app/scenes/Settings/Template.tsx +++ b/app/scenes/Settings/Template.tsx @@ -4,6 +4,7 @@ import { useEffect, useCallback, useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; import { useParams } from "react-router-dom"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper"; import { Action } from "~/components/Actions"; import Breadcrumb from "~/components/Breadcrumb"; @@ -101,7 +102,7 @@ const TemplateSetting = observer(function Template_({ template }: Props) { await template.save(); history.push(settingsPath("templates")); } catch (error) { - toast.error(error.message); + toast.error(errToString(error)); } finally { setSaving(false); } diff --git a/app/scenes/Settings/TemplateNew.tsx b/app/scenes/Settings/TemplateNew.tsx index 446c177ced..2344816e49 100644 --- a/app/scenes/Settings/TemplateNew.tsx +++ b/app/scenes/Settings/TemplateNew.tsx @@ -3,6 +3,7 @@ import { ShapesIcon } from "outline-icons"; import { useCallback, useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper"; import Template from "~/models/Template"; import { Action } from "~/components/Actions"; @@ -63,7 +64,7 @@ function TemplateNewScene() { await template.save(); history.push(settingsPath("templates")); } catch (error) { - toast.error(error.message); + toast.error(errToString(error)); } finally { setSaving(false); } diff --git a/app/scenes/Settings/components/DomainManagement.tsx b/app/scenes/Settings/components/DomainManagement.tsx index 48ad2eb2ae..68c3cb0481 100644 --- a/app/scenes/Settings/components/DomainManagement.tsx +++ b/app/scenes/Settings/components/DomainManagement.tsx @@ -4,6 +4,7 @@ import * as React from "react"; import { Trans, useTranslation } from "react-i18next"; import { toast } from "sonner"; import styled from "styled-components"; +import { errToString } from "@shared/utils/error"; import Button from "~/components/Button"; import Flex from "~/components/Flex"; import Input from "~/components/Input"; @@ -37,7 +38,7 @@ function DomainManagement({ onSuccess }: Props) { setExistingDomainsTouched(false); updateLastKnownDomainCount(allowedDomains.length); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, [team, allowedDomains, onSuccess]); diff --git a/app/scenes/Settings/components/DropToImport.tsx b/app/scenes/Settings/components/DropToImport.tsx index 8e8c30b725..7d943f8c74 100644 --- a/app/scenes/Settings/components/DropToImport.tsx +++ b/app/scenes/Settings/components/DropToImport.tsx @@ -5,6 +5,7 @@ import Dropzone from "react-dropzone"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import styled from "styled-components"; +import { errToString } from "@shared/utils/error"; import { s } from "@shared/styles"; import { AttachmentPreset, @@ -89,7 +90,7 @@ function DropToImport({ disabled, onSubmit, children, format }: Props) { ), }); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { setImporting(false); setUploadProgress(0); diff --git a/app/scenes/Settings/components/FileOperationListItem.tsx b/app/scenes/Settings/components/FileOperationListItem.tsx index 7a139fc847..092f328f46 100644 --- a/app/scenes/Settings/components/FileOperationListItem.tsx +++ b/app/scenes/Settings/components/FileOperationListItem.tsx @@ -4,6 +4,7 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import { useTheme } from "styled-components"; +import { errToString } from "@shared/utils/error"; import Spinner from "@shared/components/Spinner"; import { FileOperationFormat, @@ -72,7 +73,7 @@ const FileOperationListItem = ({ fileOperation }: Props) => { toast.success(t("Export deleted")); } } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, [fileOperation, fileOperations, t]); diff --git a/app/scenes/Settings/components/GroupDialogs.tsx b/app/scenes/Settings/components/GroupDialogs.tsx index fb8f4a9a26..d9cc9f8a66 100644 --- a/app/scenes/Settings/components/GroupDialogs.tsx +++ b/app/scenes/Settings/components/GroupDialogs.tsx @@ -3,6 +3,7 @@ import { observer } from "mobx-react"; import * as React from "react"; import { Trans, useTranslation } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import Group from "~/models/Group"; import type User from "~/models/User"; import Invite from "~/scenes/Invite"; @@ -64,7 +65,7 @@ export function CreateGroupDialog() { dialogs.closeAllModals(); history.push(settingsPath("groups", group.id, "members")); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { setIsSaving(false); } @@ -135,7 +136,7 @@ export function EditGroupDialog({ group, onSubmit }: Props) { }); onSubmit(); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { setIsSaving(false); } @@ -434,7 +435,7 @@ const GroupMemberListItem = observer(function ({ }); } } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); return false; } return true; diff --git a/app/scenes/Settings/components/ImageUpload.tsx b/app/scenes/Settings/components/ImageUpload.tsx index d5e1db53ea..fe81288e2d 100644 --- a/app/scenes/Settings/components/ImageUpload.tsx +++ b/app/scenes/Settings/components/ImageUpload.tsx @@ -6,6 +6,7 @@ import AvatarEditor from "react-avatar-editor"; import { useDropzone } from "react-dropzone"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; +import { errToString } from "@shared/utils/error"; import { s } from "@shared/styles"; import { AttachmentPreset } from "@shared/types"; import { AttachmentValidation } from "@shared/validations"; @@ -49,7 +50,7 @@ const ImageUpload: React.FC = ({ }); void onSuccess(attachment.url); } catch (err) { - onError(err.message); + onError(errToString(err)); } finally { setIsUploading(false); setIsCropping(false); diff --git a/app/scenes/Settings/components/ImportListItem.tsx b/app/scenes/Settings/components/ImportListItem.tsx index 6b098afae8..5bdef8693a 100644 --- a/app/scenes/Settings/components/ImportListItem.tsx +++ b/app/scenes/Settings/components/ImportListItem.tsx @@ -5,6 +5,7 @@ import { useMemo, useCallback } from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import { useTheme } from "styled-components"; +import { errToString } from "@shared/utils/error"; import Spinner from "@shared/components/Spinner"; import { ImportState } from "@shared/types"; import type Import from "~/models/Import"; @@ -61,7 +62,7 @@ export const ImportListItem = observer(({ importModel }: Props) => { await importModel.cancel(); toast.success(t("Import canceled")); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }; @@ -88,7 +89,7 @@ export const ImportListItem = observer(({ importModel }: Props) => { await importModel.delete(); toast.success(t("Import deleted")); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }; diff --git a/app/scenes/TeamDelete.tsx b/app/scenes/TeamDelete.tsx index 8a038d6682..9e4195cb58 100644 --- a/app/scenes/TeamDelete.tsx +++ b/app/scenes/TeamDelete.tsx @@ -3,6 +3,7 @@ import * as React from "react"; import { Controller, useForm } from "react-hook-form"; import { useTranslation, Trans } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import Button from "~/components/Button"; import Flex from "~/components/Flex"; import { OneTimePasswordInput } from "~/components/OneTimePasswordInput"; @@ -38,7 +39,7 @@ function TeamDelete({ onSubmit }: Props) { await auth.requestDeleteTeam(); setWaitingCode(true); } catch (error) { - toast.error(error.message); + toast.error(errToString(error)); } }, [auth] @@ -56,7 +57,7 @@ function TeamDelete({ onSubmit }: Props) { }); onSubmit(); } catch (error) { - toast.error(error.message); + toast.error(errToString(error)); } }, [auth, onSubmit] diff --git a/app/scenes/TeamNew.tsx b/app/scenes/TeamNew.tsx index f228190689..9d04ceb97d 100644 --- a/app/scenes/TeamNew.tsx +++ b/app/scenes/TeamNew.tsx @@ -2,6 +2,7 @@ import { observer } from "mobx-react"; import * as React from "react"; import { useTranslation, Trans } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import type User from "~/models/User"; import Button from "~/components/Button"; import Flex from "~/components/Flex"; @@ -31,7 +32,7 @@ function TeamNew({ user }: Props) { }); } } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { setIsSaving(false); } diff --git a/app/scenes/UserDelete.tsx b/app/scenes/UserDelete.tsx index 914e14e4b5..a270841daa 100644 --- a/app/scenes/UserDelete.tsx +++ b/app/scenes/UserDelete.tsx @@ -3,6 +3,7 @@ import * as React from "react"; import { Controller, useForm } from "react-hook-form"; import { useTranslation, Trans } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import Button from "~/components/Button"; import Flex from "~/components/Flex"; import { OneTimePasswordInput } from "~/components/OneTimePasswordInput"; @@ -37,7 +38,7 @@ function UserDelete({ onSubmit }: Props) { await auth.requestDeleteUser(); setWaitingCode(true); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, [auth] @@ -55,7 +56,7 @@ function UserDelete({ onSubmit }: Props) { }); onSubmit(); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, [auth, onSubmit] diff --git a/app/stores/AuthStore.ts b/app/stores/AuthStore.ts index 684cf26d01..206cfe0915 100644 --- a/app/stores/AuthStore.ts +++ b/app/stores/AuthStore.ts @@ -3,6 +3,7 @@ import invariant from "invariant"; import { isNil } from "es-toolkit/compat"; import { observable, action, computed, autorun, runInAction } from "mobx"; import { getCookie, setCookie } from "tiny-cookie"; +import { toError } from "@shared/utils/error"; import type { CustomTheme } from "@shared/types"; import Storage from "@shared/utils/Storage"; import { getCookieDomain, parseDomain } from "@shared/utils/domains"; @@ -255,9 +256,20 @@ export default class AuthStore extends Store { } }); } catch (err) { - if (err.error === "user_suspended") { + if ( + err instanceof Error && + "error" in err && + err.error === "user_suspended" + ) { this.isSuspended = true; - this.suspendedContactEmail = err.data.adminEmail; + if ( + "data" in err && + err.data instanceof Object && + "adminEmail" in err.data && + typeof err.data.adminEmail === "string" + ) { + this.suspendedContactEmail = err.data.adminEmail; + } return; } throw err; @@ -342,7 +354,7 @@ export default class AuthStore extends Store { // invalidate authentication token on server and unset auth cookie await client.post(`/auth.delete`); } catch (err) { - Logger.error("Failed to delete authentication", err); + Logger.error("Failed to delete authentication", toError(err)); } } diff --git a/app/stores/UnfurlsStore.ts b/app/stores/UnfurlsStore.ts index 0714aa8a1f..0e3ea09482 100644 --- a/app/stores/UnfurlsStore.ts +++ b/app/stores/UnfurlsStore.ts @@ -1,5 +1,6 @@ import { subMinutes } from "date-fns"; import { action } from "mobx"; +import { errToString } from "@shared/utils/error"; import type { UnfurlResourceType } from "@shared/types"; import Unfurl from "~/models/Unfurl"; import { client } from "~/utils/ApiClient"; @@ -89,7 +90,7 @@ class UnfurlsStore extends Store> { } catch (err) { Logger.warn("Failed to unfurl url", { url, - message: err.message, + message: errToString(err), }); return; } finally { diff --git a/app/typings/index.d.ts b/app/typings/index.d.ts index 38a24f9b2a..72c3d97303 100644 --- a/app/typings/index.d.ts +++ b/app/typings/index.d.ts @@ -1,5 +1,7 @@ declare module "~/utils/autotrack"; +declare module "vite/modulepreload-polyfill"; + declare module "emoji-mart"; declare module "string-replace-to-array"; diff --git a/app/typings/window.d.ts b/app/typings/window.d.ts index 23752e23ad..d5a17b6a0a 100644 --- a/app/typings/window.d.ts +++ b/app/typings/window.d.ts @@ -1,3 +1,4 @@ +/// import type RootStore from "~/stores/RootStore"; declare global { diff --git a/app/utils/download.ts b/app/utils/download.ts index a85d25159d..ddd82cb68c 100644 --- a/app/utils/download.ts +++ b/app/utils/download.ts @@ -5,6 +5,7 @@ // v3 added dataURL and Blob Input, bind-toggle arity, and legacy dataURL fallback was improved with force-download mime and base64 support // data can be a string, Blob, File, or dataURL export default function download( + this: unknown, data: Blob | string | File, strFileName: string, strMimeType?: string diff --git a/package.json b/package.json index a3f35cf781..b60b6bf10c 100644 --- a/package.json +++ b/package.json @@ -375,7 +375,7 @@ "rimraf": "^6.1.3", "rollup-plugin-webpack-stats": "2.1.11", "terser": "^5.48.0", - "typescript": "^5.9.3", + "typescript": "^6.0.3", "unplugin-swc": "^1.5.9", "vite-plugin-babel": "^1.7.3", "vite-tsconfig-paths": "^6.1.1", diff --git a/plugins/azure/server/auth/azure.ts b/plugins/azure/server/auth/azure.ts index aa7c5e1af6..aa56a71a6c 100644 --- a/plugins/azure/server/auth/azure.ts +++ b/plugins/azure/server/auth/azure.ts @@ -4,6 +4,7 @@ import jwt from "jsonwebtoken"; import type { Context } from "koa"; import Router from "koa-router"; import type { Profile } from "passport"; +import { toError } from "@shared/utils/error"; import { slugifyDomain } from "@shared/utils/domains"; import { parseEmail } from "@shared/utils/email"; import accountProvisioner from "@server/commands/accountProvisioner"; @@ -226,7 +227,7 @@ if (env.AZURE_CLIENT_ID && env.AZURE_CLIENT_SECRET) { return done(null, result.user, { ...result, client }); } catch (err) { - return done(err, null); + return done(toError(err), null); } } ); diff --git a/plugins/diagrams/client/Settings.tsx b/plugins/diagrams/client/Settings.tsx index 23ac7ddeba..76f6a47526 100644 --- a/plugins/diagrams/client/Settings.tsx +++ b/plugins/diagrams/client/Settings.tsx @@ -4,6 +4,7 @@ import * as React from "react"; import { useForm } from "react-hook-form"; import { useTranslation, Trans } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import { IntegrationType, IntegrationService } from "@shared/types"; import type Integration from "~/models/Integration"; import { IntegrationScene } from "~/scenes/Settings/components/IntegrationScene"; @@ -67,7 +68,7 @@ function DiagramsNet() { toast.success(t("Settings saved")); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, [integrations, integration, t] diff --git a/plugins/discord/server/auth/discord.ts b/plugins/discord/server/auth/discord.ts index c2a9e73f87..33b670e2d2 100644 --- a/plugins/discord/server/auth/discord.ts +++ b/plugins/discord/server/auth/discord.ts @@ -9,6 +9,7 @@ import type { Context } from "koa"; import Router from "koa-router"; import { Strategy } from "passport-oauth2"; +import { toError } from "@shared/utils/error"; import { languages } from "@shared/i18n"; import { slugifyDomain } from "@shared/utils/domains"; import { parseEmail } from "@shared/utils/email"; @@ -220,7 +221,7 @@ if (env.DISCORD_CLIENT_ID && env.DISCORD_CLIENT_SECRET) { }); return done(null, result.user, { ...result, client }); } catch (err) { - return done(err, null); + return done(toError(err), null); } } ) diff --git a/plugins/email/server/auth/email.ts b/plugins/email/server/auth/email.ts index c418e0d64b..9454444fe8 100644 --- a/plugins/email/server/auth/email.ts +++ b/plugins/email/server/auth/email.ts @@ -1,4 +1,5 @@ import Router from "koa-router"; +import { errToString } from "@shared/utils/error"; import { Client, NotificationEventType } from "@shared/types"; import { parseDomain } from "@shared/utils/domains"; import InviteAcceptedEmail from "@server/emails/templates/InviteAcceptedEmail"; @@ -161,8 +162,11 @@ const emailCallback = async (ctx: APIContext) => { return; } } catch (err) { - Logger.debug("authentication", err); - return ctx.redirect(`/?notice=auth-error&description=${err.message}`); + const message = errToString(err); + Logger.debug("authentication", message); + return ctx.redirect( + `/?notice=auth-error&description=${encodeURIComponent(message)}` + ); } if (!user) { diff --git a/plugins/figma/server/api/figma.ts b/plugins/figma/server/api/figma.ts index 9786c693b3..3ec95f74a0 100644 --- a/plugins/figma/server/api/figma.ts +++ b/plugins/figma/server/api/figma.ts @@ -1,3 +1,4 @@ +import { toError } from "@shared/utils/error"; import auth from "@server/middlewares/authentication"; import Router from "koa-router"; import * as T from "./schema"; @@ -102,7 +103,10 @@ router.get( ctx.redirect(FigmaUtils.successUrl()); } catch (err) { - Logger.error("Encountered error during Figma OAuth callback", err); + Logger.error( + "Encountered error during Figma OAuth callback", + toError(err) + ); ctx.redirect(FigmaUtils.errorUrl("unknown")); } } diff --git a/plugins/figma/server/figma.ts b/plugins/figma/server/figma.ts index 569636908a..5c28ac63e6 100644 --- a/plugins/figma/server/figma.ts +++ b/plugins/figma/server/figma.ts @@ -1,4 +1,5 @@ import { z } from "zod"; +import { toError } from "@shared/utils/error"; import fetch from "@server/utils/fetch"; import env from "./env"; import { FigmaUtils } from "../shared/FigmaUtils"; @@ -173,7 +174,7 @@ export class Figma { } catch (err) { Logger.error( `Error fetching Figma file metadata for integration ${integration.id}`, - err + toError(err) ); } } diff --git a/plugins/github/server/github.ts b/plugins/github/server/github.ts index f25aba9e51..fcb067675c 100644 --- a/plugins/github/server/github.ts +++ b/plugins/github/server/github.ts @@ -8,6 +8,7 @@ import { Sequelize } from "sequelize"; import type { Endpoints, OctokitResponse } from "@octokit/types"; import { Octokit } from "octokit"; import pluralize from "pluralize"; +import { toError, errToString } from "@shared/utils/error"; import type { IntegrationType } from "@shared/types"; import { IntegrationService, UnfurlResourceType } from "@shared/types"; import Logger from "@server/logging/Logger"; @@ -385,8 +386,10 @@ export class GitHub { return GitHub.transformData(res.data, resource.type); } catch (err) { - Logger.warn("Failed to fetch resource from GitHub", err); - return { error: err.message || "Unknown error" }; + Logger.warn("Failed to fetch resource from GitHub", toError(err)); + return { + error: errToString(err) || "Unknown error", + }; } }; @@ -398,7 +401,7 @@ export class GitHub { try { project = await client.requestProject(resource); } catch (err) { - Logger.warn("Failed to fetch project from GitHub", err); + Logger.warn("Failed to fetch project from GitHub", toError(err)); return { error: "Resource not found" }; } diff --git a/plugins/gitlab/client/components/GitLabConnectDialog.tsx b/plugins/gitlab/client/components/GitLabConnectDialog.tsx index 03b3c62032..da60ddca99 100644 --- a/plugins/gitlab/client/components/GitLabConnectDialog.tsx +++ b/plugins/gitlab/client/components/GitLabConnectDialog.tsx @@ -2,6 +2,7 @@ import * as React from "react"; import { useTranslation, Trans } from "react-i18next"; import styled from "styled-components"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import { s } from "@shared/styles"; import Button from "~/components/Button"; import Flex from "~/components/Flex"; @@ -39,7 +40,7 @@ function GitLabConnectDialog() { dialogs.closeAllModals(); redirectTo(res.data.redirectUrl); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { setSaving(false); } diff --git a/plugins/gitlab/server/GitLabIssueProvider.ts b/plugins/gitlab/server/GitLabIssueProvider.ts index 390a376a70..2bb6425443 100644 --- a/plugins/gitlab/server/GitLabIssueProvider.ts +++ b/plugins/gitlab/server/GitLabIssueProvider.ts @@ -1,3 +1,4 @@ +import { toError } from "@shared/utils/error"; import type { IssueSource } from "@shared/schema"; import { IntegrationService, type IntegrationType } from "@shared/types"; import Logger from "@server/logging/Logger"; @@ -69,7 +70,7 @@ export class GitLabIssueProvider extends BaseIssueProvider { })) ); } catch (err) { - Logger.warn("Failed to fetch projects from GitLab", err); + Logger.warn("Failed to fetch projects from GitLab", toError(err)); } return sources; diff --git a/plugins/gitlab/server/api/gitlab.ts b/plugins/gitlab/server/api/gitlab.ts index c1a74dd7f8..fb50b85b17 100644 --- a/plugins/gitlab/server/api/gitlab.ts +++ b/plugins/gitlab/server/api/gitlab.ts @@ -1,5 +1,6 @@ import Router from "koa-router"; import { Op } from "sequelize"; +import { toError } from "@shared/utils/error"; import { IntegrationService, IntegrationType } from "@shared/types"; import { createContext } from "@server/context"; import { ValidationError } from "@server/errors"; @@ -284,7 +285,10 @@ router.get( ctx.redirect(GitLabUtils.url); } catch (err) { - Logger.error("Encountered error during Gitlab OAuth callback", err); + Logger.error( + "Encountered error during Gitlab OAuth callback", + toError(err) + ); ctx.redirect(GitLabUtils.errorUrl("unauthenticated")); } } diff --git a/plugins/gitlab/server/gitlab.ts b/plugins/gitlab/server/gitlab.ts index 2f90abe6c7..ae3528cebb 100644 --- a/plugins/gitlab/server/gitlab.ts +++ b/plugins/gitlab/server/gitlab.ts @@ -11,6 +11,7 @@ import { IntegrationService, UnfurlResourceType, } from "@shared/types"; +import { toError, errToString } from "@shared/utils/error"; import Logger from "@server/logging/Logger"; import type { User } from "@server/models"; import { Integration, IntegrationAuthentication } from "@server/models"; @@ -267,8 +268,10 @@ export class GitLab { return { error: "Resource not found" }; } catch (err) { - Logger.warn("Failed to fetch resource from GitLab", err); - return { error: err.message || "Unknown error" }; + Logger.warn("Failed to fetch resource from GitLab", toError(err)); + return { + error: errToString(err) || "Unknown error", + }; } }; diff --git a/plugins/google/server/auth/google.ts b/plugins/google/server/auth/google.ts index 8e4d0f83c0..ec3c0fa775 100644 --- a/plugins/google/server/auth/google.ts +++ b/plugins/google/server/auth/google.ts @@ -4,6 +4,7 @@ import Router from "koa-router"; import { capitalize } from "es-toolkit/compat"; import type { Profile } from "passport"; import { Strategy as GoogleStrategy } from "passport-google-oauth2"; +import { toError } from "@shared/utils/error"; import { languages } from "@shared/i18n"; import { slugifyDomain } from "@shared/utils/domains"; import accountProvisioner from "@server/commands/accountProvisioner"; @@ -159,7 +160,7 @@ if (env.GOOGLE_CLIENT_ID && env.GOOGLE_CLIENT_SECRET) { return done(null, result.user, { ...result, client }); } catch (err) { - return done(err, null); + return done(toError(err), null); } } ) diff --git a/plugins/googleanalytics/client/Settings.tsx b/plugins/googleanalytics/client/Settings.tsx index 1a8b885eb4..de046e3e17 100644 --- a/plugins/googleanalytics/client/Settings.tsx +++ b/plugins/googleanalytics/client/Settings.tsx @@ -4,6 +4,7 @@ import * as React from "react"; import { useForm } from "react-hook-form"; import { useTranslation, Trans } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import { IntegrationType, IntegrationService } from "@shared/types"; import type Integration from "~/models/Integration"; import { IntegrationScene } from "~/scenes/Settings/components/IntegrationScene"; @@ -63,7 +64,7 @@ function GoogleAnalytics() { toast.success(t("Settings saved")); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, [integrations, integration, t] diff --git a/plugins/iframely/server/iframely.ts b/plugins/iframely/server/iframely.ts index 13f7930578..cdf784e6b0 100644 --- a/plugins/iframely/server/iframely.ts +++ b/plugins/iframely/server/iframely.ts @@ -1,3 +1,4 @@ +import { toError, errToString } from "@shared/utils/error"; import type { JSONObject } from "@shared/types"; import { UnfurlResourceType } from "@shared/types"; import Logger from "@server/logging/Logger"; @@ -29,8 +30,13 @@ class Iframely { ); return await res.json(); } catch (err) { - Logger.error(`Error fetching data from Iframely for url: ${url}`, err); - return { error: err.message || "Unknown error" }; + Logger.error( + `Error fetching data from Iframely for url: ${url}`, + toError(err) + ); + return { + error: errToString(err) || "Unknown error", + }; } } diff --git a/plugins/linear/server/api/linear.ts b/plugins/linear/server/api/linear.ts index ab10230011..03c64c5ac5 100644 --- a/plugins/linear/server/api/linear.ts +++ b/plugins/linear/server/api/linear.ts @@ -1,4 +1,5 @@ import Router from "koa-router"; +import { toError } from "@shared/utils/error"; import { IntegrationService, IntegrationType } from "@shared/types"; import { ValidationError } from "@server/errors"; import Logger from "@server/logging/Logger"; @@ -107,7 +108,10 @@ router.get( ctx.redirect(LinearUtils.successUrl()); } catch (err) { - Logger.error("Encountered error during Linear OAuth callback", err); + Logger.error( + "Encountered error during Linear OAuth callback", + toError(err) + ); ctx.redirect(LinearUtils.errorUrl("unknown")); } } diff --git a/plugins/linear/server/linear.ts b/plugins/linear/server/linear.ts index 85a8376430..ff4da75d0d 100644 --- a/plugins/linear/server/linear.ts +++ b/plugins/linear/server/linear.ts @@ -1,5 +1,6 @@ import type { Issue, WorkflowState } from "@linear/sdk"; import { LinearClient } from "@linear/sdk"; +import { toError } from "@shared/utils/error"; import fetch from "@server/utils/fetch"; import { sortBy } from "es-toolkit/compat"; import { z } from "zod"; @@ -155,8 +156,9 @@ export class Linear { return; } } catch (err) { - Logger.warn("Failed to fetch resource from Linear", err); - return { error: err.message || "Unknown error" }; + const error = toError(err); + Logger.warn("Failed to fetch resource from Linear", error); + return { error: error.message || "Unknown error" }; } }; diff --git a/plugins/linear/server/uninstall.ts b/plugins/linear/server/uninstall.ts index 7c3108576a..aba0d8f533 100644 --- a/plugins/linear/server/uninstall.ts +++ b/plugins/linear/server/uninstall.ts @@ -1,3 +1,4 @@ +import { toError } from "@shared/utils/error"; import type { IntegrationType } from "@shared/types"; import { IntegrationService } from "@shared/types"; import Logger from "@server/logging/Logger"; @@ -21,6 +22,6 @@ export async function uninstall( await Linear.revokeAccess(authentication.token); } catch (err) { // suppress error since this is a best-effort operation. - Logger.error("Failed to revoke Linear access token", err); + Logger.error("Failed to revoke Linear access token", toError(err)); } } diff --git a/plugins/matomo/client/Settings.tsx b/plugins/matomo/client/Settings.tsx index 2c1a2e3e59..7de1f35699 100644 --- a/plugins/matomo/client/Settings.tsx +++ b/plugins/matomo/client/Settings.tsx @@ -4,6 +4,7 @@ import * as React from "react"; import { useForm } from "react-hook-form"; import { useTranslation, Trans } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import { IntegrationType, IntegrationService } from "@shared/types"; import type Integration from "~/models/Integration"; import { IntegrationScene } from "~/scenes/Settings/components/IntegrationScene"; @@ -71,7 +72,7 @@ function Matomo() { toast.success(t("Settings saved")); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, [integrations, integration, t] diff --git a/plugins/notion/client/components/ImportDialog.tsx b/plugins/notion/client/components/ImportDialog.tsx index 64d3562e9d..b3d9c4e3fc 100644 --- a/plugins/notion/client/components/ImportDialog.tsx +++ b/plugins/notion/client/components/ImportDialog.tsx @@ -1,6 +1,7 @@ import React from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import type { ImportInput } from "@shared/schema"; import type { CollectionPermission } from "@shared/types"; import { IntegrationService } from "@shared/types"; @@ -50,7 +51,7 @@ export function ImportDialog({ integrationId, onSubmit }: Props) { onSubmit(); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); resetSubmitting(); } }, [ diff --git a/plugins/oidc/server/auth/oidc.ts b/plugins/oidc/server/auth/oidc.ts index 13df3df081..bee28857af 100644 --- a/plugins/oidc/server/auth/oidc.ts +++ b/plugins/oidc/server/auth/oidc.ts @@ -1,4 +1,5 @@ import Router from "koa-router"; +import { toError } from "@shared/utils/error"; import Logger from "@server/logging/Logger"; import env from "../env"; import { fetchOIDCConfiguration } from "../oidcDiscovery"; @@ -63,7 +64,7 @@ if (hasManualConfig) { return router; } catch (error) { - Logger.fatal("Failed to discover OIDC configuration", error); + Logger.fatal("Failed to discover OIDC configuration", toError(error)); throw error; } })(); diff --git a/plugins/oidc/server/auth/oidcRouter.ts b/plugins/oidc/server/auth/oidcRouter.ts index 131b5300eb..07aba58190 100644 --- a/plugins/oidc/server/auth/oidcRouter.ts +++ b/plugins/oidc/server/auth/oidcRouter.ts @@ -3,6 +3,7 @@ import JWT from "jsonwebtoken"; import type { Context } from "koa"; import type Router from "koa-router"; import { get } from "es-toolkit/compat"; +import { toError } from "@shared/utils/error"; import { slugifyDomain } from "@shared/utils/domains"; import { parseEmail } from "@shared/utils/email"; import { isBase64Url } from "@shared/utils/urls"; @@ -110,7 +111,7 @@ export function createOIDCRouter( sub?: string; }; } catch (err) { - Logger.error("id_token decode threw error: ", err); + Logger.error("id_token decode threw error: ", toError(err)); return {}; } })(); @@ -233,7 +234,7 @@ export function createOIDCRouter( }); return done(null, result.user, { ...result, client }); } catch (err) { - return done(err, null); + return done(toError(err), null); } } ) diff --git a/plugins/oidc/server/oidcDiscovery.ts b/plugins/oidc/server/oidcDiscovery.ts index 61d66aa37e..5474eb95ea 100644 --- a/plugins/oidc/server/oidcDiscovery.ts +++ b/plugins/oidc/server/oidcDiscovery.ts @@ -1,3 +1,4 @@ +import { toError } from "@shared/utils/error"; import { InternalError } from "@server/errors"; import Logger from "@server/logging/Logger"; import fetch from "@server/utils/fetch"; @@ -85,7 +86,7 @@ export async function fetchOIDCConfiguration( return config; } catch (error) { - Logger.error("Failed to fetch OIDC configuration", error); + Logger.error("Failed to fetch OIDC configuration", toError(error)); throw error; } } diff --git a/plugins/passkeys/client/Settings.tsx b/plugins/passkeys/client/Settings.tsx index 4b96b1f0ef..dd736ee1ba 100644 --- a/plugins/passkeys/client/Settings.tsx +++ b/plugins/passkeys/client/Settings.tsx @@ -1,4 +1,5 @@ import { startRegistration } from "@simplewebauthn/browser"; +import { errToString } from "@shared/utils/error"; import type { JSONObject } from "@shared/types"; import { observer } from "mobx-react"; import { KeyIcon, PlusIcon } from "outline-icons"; @@ -78,7 +79,7 @@ function PasskeysSettings() { await loadPasskeys(); } catch (err) { toast.error( - err.message || t("Failed to register passkey. Please try again.") + errToString(err) || t("Failed to register passkey. Please try again.") ); } finally { setIsRegistering(false); @@ -113,7 +114,8 @@ function PasskeysSettings() { await loadPasskeys(); } catch (err) { toast.error( - err.message || t("Failed to delete passkey. Please try again.") + errToString(err) || + t("Failed to delete passkey. Please try again.") ); } }} diff --git a/plugins/passkeys/client/components/RenamePasskeyDialog.tsx b/plugins/passkeys/client/components/RenamePasskeyDialog.tsx index 38bd6033f1..9746ec34e2 100644 --- a/plugins/passkeys/client/components/RenamePasskeyDialog.tsx +++ b/plugins/passkeys/client/components/RenamePasskeyDialog.tsx @@ -2,6 +2,7 @@ import { observer } from "mobx-react"; import * as React from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import Button from "~/components/Button"; import Flex from "~/components/Flex"; import Input from "~/components/Input"; @@ -44,7 +45,7 @@ function RenamePasskeyDialog({ onSuccess(); } catch (err) { toast.error( - err.message || t("Failed to update passkey. Please try again.") + errToString(err) || t("Failed to update passkey. Please try again.") ); } finally { setIsSaving(false); diff --git a/plugins/passkeys/server/auth/passkeys.ts b/plugins/passkeys/server/auth/passkeys.ts index c7b4fd4405..621326987f 100644 --- a/plugins/passkeys/server/auth/passkeys.ts +++ b/plugins/passkeys/server/auth/passkeys.ts @@ -8,6 +8,7 @@ import { isoBase64URL } from "@simplewebauthn/server/helpers"; import type { AuthenticatorTransportFuture } from "@simplewebauthn/server"; import Router from "koa-router"; import { randomBytes } from "node:crypto"; +import { toError } from "@shared/utils/error"; import { User, UserPasskey, Team } from "@server/models"; import auth from "@server/middlewares/authentication"; import validate from "@server/middlewares/validate"; @@ -156,7 +157,7 @@ router.post( expectedRPID: getRpID(ctx), }); } catch (error) { - const err = error instanceof Error ? error : new Error(String(error)); + const err = toError(error); Logger.error("passkeys: Registration verification failed", err); throw ValidationError(err.message); } @@ -306,7 +307,10 @@ router.post( }, }); } catch (err) { - Logger.error("passkeys: Authentication verification failed", err); + Logger.error( + "passkeys: Authentication verification failed", + toError(err) + ); throw ValidationError("Passkey authentication failed. Please try again."); } diff --git a/plugins/search-postgres/server/PostgresSearchProvider.ts b/plugins/search-postgres/server/PostgresSearchProvider.ts index 0be0eef517..49653aeb5f 100644 --- a/plugins/search-postgres/server/PostgresSearchProvider.ts +++ b/plugins/search-postgres/server/PostgresSearchProvider.ts @@ -264,7 +264,10 @@ export default class PostgresSearchProvider extends BaseSearchProvider { count, }); } catch (err) { - if (err.message.includes("syntax error in tsquery")) { + if ( + err instanceof Error && + err.message.includes("syntax error in tsquery") + ) { throw ValidationError("Invalid search query"); } throw err; @@ -456,7 +459,10 @@ export default class PostgresSearchProvider extends BaseSearchProvider { count, }); } catch (err) { - if (err.message.includes("syntax error in tsquery")) { + if ( + err instanceof Error && + err.message.includes("syntax error in tsquery") + ) { throw ValidationError("Invalid search query"); } throw err; diff --git a/plugins/slack/server/api/hooks.ts b/plugins/slack/server/api/hooks.ts index 95a86873cd..3c1431f522 100644 --- a/plugins/slack/server/api/hooks.ts +++ b/plugins/slack/server/api/hooks.ts @@ -3,6 +3,7 @@ import Router from "koa-router"; import { escapeRegExp } from "es-toolkit/compat"; import queryString from "query-string"; import { z } from "zod"; +import { toError } from "@shared/utils/error"; import { IntegrationService, IntegrationType } from "@shared/types"; import parseDocumentSlug from "@shared/utils/parseDocumentSlug"; import { @@ -155,7 +156,7 @@ router.post( callback_id = parsed.callback_id; token = parsed.token; } catch (err) { - Logger.error("Failed to parse Slack interactive payload", err, { + Logger.error("Failed to parse Slack interactive payload", toError(err), { payload, }); throw ValidationError("Invalid payload"); diff --git a/plugins/slack/server/auth/slack.ts b/plugins/slack/server/auth/slack.ts index b33c6cf53f..06d31a9cc5 100644 --- a/plugins/slack/server/auth/slack.ts +++ b/plugins/slack/server/auth/slack.ts @@ -3,6 +3,7 @@ import type { Context } from "koa"; import Router from "koa-router"; import type { Profile } from "passport"; import { Strategy as SlackStrategy } from "passport-slack-oauth2"; +import { toError } from "@shared/utils/error"; import { IntegrationService, IntegrationType } from "@shared/types"; import accountProvisioner from "@server/commands/accountProvisioner"; import { ValidationError } from "@server/errors"; @@ -128,7 +129,7 @@ if (env.SLACK_CLIENT_ID && env.SLACK_CLIENT_SECRET) { }); return done(null, result.user, { ...result, client }); } catch (err) { - return done(err, null); + return done(toError(err), null); } } ); diff --git a/plugins/slack/server/slack.ts b/plugins/slack/server/slack.ts index 2bb6c984a3..41a0fe3852 100644 --- a/plugins/slack/server/slack.ts +++ b/plugins/slack/server/slack.ts @@ -1,4 +1,5 @@ import querystring, { type ParsedUrlQueryInput } from "node:querystring"; +import { errToString } from "@shared/utils/error"; import { InvalidRequestError } from "@server/errors"; import fetch from "@server/utils/fetch"; import { SlackUtils } from "../shared/SlackUtils"; @@ -31,7 +32,7 @@ export async function post( }); data = await response.json(); } catch (err) { - throw InvalidRequestError(err.message); + throw InvalidRequestError(errToString(err)); } if (!data.ok) { @@ -76,7 +77,7 @@ export async function request( }); data = await response.json(); } catch (err) { - throw InvalidRequestError(err.message); + throw InvalidRequestError(errToString(err)); } if (!data.ok) { diff --git a/plugins/storage/server/api/files.ts b/plugins/storage/server/api/files.ts index 009ffccfd1..9bfe73fe99 100644 --- a/plugins/storage/server/api/files.ts +++ b/plugins/storage/server/api/files.ts @@ -70,7 +70,7 @@ router.post( try { await attachment.writeFile(file); } catch (err) { - if (err.message.includes("permission denied")) { + if (err instanceof Error && err.message.includes("permission denied")) { throw Error( `Permission denied writing to "${key}". Check the host machine file system permissions.` ); diff --git a/plugins/storage/server/index.ts b/plugins/storage/server/index.ts index f428f3a899..d5a9f20321 100644 --- a/plugins/storage/server/index.ts +++ b/plugins/storage/server/index.ts @@ -1,4 +1,5 @@ import { existsSync, mkdirSync } from "node:fs"; +import { toError } from "@shared/utils/error"; import env from "@server/env"; import Logger from "@server/logging/Logger"; import { @@ -18,7 +19,7 @@ if (env.FILE_STORAGE === "local") { } catch (err) { Logger.fatal( `Failed to create directory for local file storage at ${env.FILE_STORAGE_LOCAL_ROOT_DIR}`, - err + toError(err) ); } } diff --git a/plugins/umami/client/Settings.tsx b/plugins/umami/client/Settings.tsx index c89c0a938f..0f26e79e06 100644 --- a/plugins/umami/client/Settings.tsx +++ b/plugins/umami/client/Settings.tsx @@ -4,6 +4,7 @@ import * as React from "react"; import { useForm } from "react-hook-form"; import { useTranslation, Trans } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import { IntegrationType, IntegrationService } from "@shared/types"; import type Integration from "~/models/Integration"; import { IntegrationScene } from "~/scenes/Settings/components/IntegrationScene"; @@ -75,7 +76,7 @@ function Umami() { toast.success(t("Settings saved")); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, [integrations, integration, t] diff --git a/plugins/webhooks/client/components/WebhookSubscriptionEdit.tsx b/plugins/webhooks/client/components/WebhookSubscriptionEdit.tsx index 5d224812a2..5204b50406 100644 --- a/plugins/webhooks/client/components/WebhookSubscriptionEdit.tsx +++ b/plugins/webhooks/client/components/WebhookSubscriptionEdit.tsx @@ -1,6 +1,7 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import type WebhookSubscription from "~/models/WebhookSubscription"; import WebhookSubscriptionForm from "./WebhookSubscriptionForm"; @@ -33,7 +34,7 @@ function WebhookSubscriptionEdit({ onSubmit, webhookSubscription }: Props) { toast.success(t("Webhook updated")); onSubmit(); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, [t, onSubmit, webhookSubscription] diff --git a/plugins/webhooks/client/components/WebhookSubscriptionNew.tsx b/plugins/webhooks/client/components/WebhookSubscriptionNew.tsx index 4acdc67a1a..306074ff58 100644 --- a/plugins/webhooks/client/components/WebhookSubscriptionNew.tsx +++ b/plugins/webhooks/client/components/WebhookSubscriptionNew.tsx @@ -1,6 +1,7 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import useStores from "~/hooks/useStores"; import WebhookSubscriptionForm from "./WebhookSubscriptionForm"; @@ -32,7 +33,7 @@ function WebhookSubscriptionNew({ onSubmit }: Props) { toast.success(t("Webhook created")); onSubmit(); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, [t, onSubmit, webhookSubscriptions] diff --git a/plugins/webhooks/server/tasks/DeliverWebhookTask.ts b/plugins/webhooks/server/tasks/DeliverWebhookTask.ts index 7fe6f088f0..d622995911 100644 --- a/plugins/webhooks/server/tasks/DeliverWebhookTask.ts +++ b/plugins/webhooks/server/tasks/DeliverWebhookTask.ts @@ -1,5 +1,6 @@ import { FetchError } from "node-fetch"; import { Op } from "sequelize"; +import { toError } from "@shared/utils/error"; import { colorPalette } from "@shared/utils/collections"; import WebhookDisabledEmail from "@server/emails/templates/WebhookDisabledEmail"; import env from "@server/env"; @@ -815,13 +816,14 @@ export default class DeliverWebhookTask extends BaseTask { }); status = response.ok ? "success" : "failed"; } catch (err) { + const error = toError(err); if (isExpectedNetworkError(err) && env.isCloudHosted) { - Logger.warn(`Failed to send webhook: ${err.message}`, { + Logger.warn(`Failed to send webhook: ${error.message}`, { event, deliveryId: delivery.id, }); } else { - Logger.error("Failed to send webhook", err, { + Logger.error("Failed to send webhook", error, { event, deliveryId: delivery.id, }); @@ -857,10 +859,14 @@ export default class DeliverWebhookTask extends BaseTask { try { await this.checkAndDisableSubscription(subscription); } catch (err) { - Logger.error("Failed to check and disable recent deliveries", err, { - event, - deliveryId: delivery.id, - }); + Logger.error( + "Failed to check and disable recent deliveries", + toError(err), + { + event, + deliveryId: delivery.id, + } + ); } } } diff --git a/server/__mocks__/bull.ts b/server/__mocks__/bull.ts index aea7a2f13b..1fe4350589 100644 --- a/server/__mocks__/bull.ts +++ b/server/__mocks__/bull.ts @@ -1,4 +1,6 @@ export default class Queue { + handler?: (job: unknown, done: () => void) => void; + done() { // } @@ -15,7 +17,7 @@ export default class Queue { return 0; } - add = function (data: unknown) { + add(data: unknown) { const job = this.createJob(data); if (!this.handler) { @@ -23,19 +25,19 @@ export default class Queue { } this.handler(job, this.done); - }; + } - process = function (handler: (job: unknown, done: () => void) => void) { + process(handler: (job: unknown, done: () => void) => void) { if (this.handler) { throw Error("Cannot define a handler more than once per Queue instance"); } this.handler = handler; - }; + } - createJob = function (data: unknown) { + createJob(data: unknown) { return { data, }; - }; + } } diff --git a/server/collaboration/PersistenceExtension.ts b/server/collaboration/PersistenceExtension.ts index 1362bc93de..b73e697b88 100644 --- a/server/collaboration/PersistenceExtension.ts +++ b/server/collaboration/PersistenceExtension.ts @@ -5,6 +5,7 @@ import type { Extension, } from "@hocuspocus/server"; import * as Y from "yjs"; +import { toError } from "@shared/utils/error"; import Logger from "@server/logging/Logger"; import { trace } from "@server/logging/tracing"; import Document from "@server/models/Document"; @@ -135,7 +136,7 @@ export default class PersistenceExtension implements Extension { clientVersion, }); } catch (err) { - Logger.error("Unable to persist document", err, { + Logger.error("Unable to persist document", toError(err), { documentId, userId: context.user?.id, }); diff --git a/server/commands/accountProvisioner.test.ts b/server/commands/accountProvisioner.test.ts index 9be87981d2..32fec40274 100644 --- a/server/commands/accountProvisioner.test.ts +++ b/server/commands/accountProvisioner.test.ts @@ -1,5 +1,6 @@ import { faker } from "@faker-js/faker"; import { randomUUID } from "node:crypto"; +import { errToString } from "@shared/utils/error"; import { TeamDomain } from "@server/models"; import Collection from "@server/models/Collection"; import UserAuthentication from "@server/models/UserAuthentication"; @@ -184,7 +185,9 @@ describe("accountProvisioner", () => { } expect(error).toBeTruthy(); - expect(error.id).toEqual("invalid_authentication"); + expect( + error instanceof Error && "id" in error ? error.id : undefined + ).toEqual("invalid_authentication"); }); it("should throw an error when authentication provider is disabled", async () => { @@ -533,7 +536,7 @@ describe("accountProvisioner", () => { error = err; } - expect(error.message).toEqual("Invalid authentication"); + expect(errToString(error)).toEqual("Invalid authentication"); }); it("should always use existing team if self-hosted", async () => { diff --git a/server/commands/accountProvisioner.ts b/server/commands/accountProvisioner.ts index 7a81d1231d..6fc22929e3 100644 --- a/server/commands/accountProvisioner.ts +++ b/server/commands/accountProvisioner.ts @@ -1,6 +1,7 @@ import path from "node:path"; import { readFile } from "fs-extra"; import invariant from "invariant"; +import { toError, errToString } from "@shared/utils/error"; import { CollectionPermission, UserRole } from "@shared/types"; import env from "@server/env"; import { @@ -136,7 +137,11 @@ async function accountProvisioner( } catch (err) { // The account could not be provisioned for the provided teamId // check to see if we can try authentication using email matching only - if (err.id === "invalid_authentication") { + if ( + err instanceof Error && + "id" in err && + err.id === "invalid_authentication" + ) { const authProvider = await AuthenticationProvider.findOne({ where: { name: authenticationProviderParams.name, @@ -163,10 +168,10 @@ async function accountProvisioner( } if (!result) { - if (err.id) { + if (err instanceof Error && "id" in err && err.id) { throw err; } else { - throw InvalidAuthenticationError(err.message); + throw InvalidAuthenticationError(errToString(err)); } } } @@ -260,7 +265,7 @@ async function accountProvisioner( }); } catch (err) { // Group sync failure should never block login - Logger.error("Group sync failed during login", err, { + Logger.error("Group sync failed during login", toError(err), { userId: user.id, provider: authenticationProviderParams.name, }); diff --git a/server/commands/documentImporter.test.ts b/server/commands/documentImporter.test.ts index 1f6a32f067..6e81b3ac25 100644 --- a/server/commands/documentImporter.test.ts +++ b/server/commands/documentImporter.test.ts @@ -1,5 +1,6 @@ import path from "node:path"; import fs from "fs-extra"; +import { errToString } from "@shared/utils/error"; import { createContext } from "@server/context"; import Attachment from "@server/models/Attachment"; import { sequelize } from "@server/storage/database"; @@ -103,7 +104,7 @@ describe("documentImporter", () => { }) ); } catch (err) { - error = err.message; + error = errToString(err); } expect(error).toEqual("File type application/octet-stream not supported"); @@ -278,7 +279,7 @@ describe("documentImporter", () => { }) ); } catch (err) { - error = err.message; + error = errToString(err); } expect(error).toEqual("File type executable/zip not supported"); diff --git a/server/commands/documentPermanentDeleter.test.ts b/server/commands/documentPermanentDeleter.test.ts index eaa13ccb3a..af6809bfca 100644 --- a/server/commands/documentPermanentDeleter.test.ts +++ b/server/commands/documentPermanentDeleter.test.ts @@ -1,4 +1,5 @@ import { subDays } from "date-fns"; +import { errToString } from "@shared/utils/error"; import { Attachment, Document } from "@server/models"; import { buildAttachment, buildDocument } from "@server/test/factories"; import { mockTaskSchedule } from "@server/test/support"; @@ -33,7 +34,7 @@ describe("documentPermanentDeleter", () => { try { await documentPermanentDeleter([document]); } catch (err) { - error = err.message; + error = errToString(err); } expect(error).toEqual( diff --git a/server/commands/teamPermanentDeleter.test.ts b/server/commands/teamPermanentDeleter.test.ts index b1b5730427..4b83b008e8 100644 --- a/server/commands/teamPermanentDeleter.test.ts +++ b/server/commands/teamPermanentDeleter.test.ts @@ -14,6 +14,7 @@ import { buildDocument, buildImport, } from "@server/test/factories"; +import { errToString } from "@shared/utils/error"; import teamPermanentDeleter from "./teamPermanentDeleter"; describe("teamPermanentDeleter", () => { @@ -207,7 +208,7 @@ describe("teamPermanentDeleter", () => { try { await teamPermanentDeleter(team); } catch (err) { - error = err.message; + error = errToString(err); } expect(error).toEqual( diff --git a/server/commands/teamProvisioner.test.ts b/server/commands/teamProvisioner.test.ts index 7f514a4e8d..1505e7cc82 100644 --- a/server/commands/teamProvisioner.test.ts +++ b/server/commands/teamProvisioner.test.ts @@ -151,7 +151,9 @@ describe("teamProvisioner", () => { } catch (e) { error = e; } - expect(error.id).toEqual("invalid_authentication"); + expect( + error instanceof Error && "id" in error ? error.id : undefined + ).toEqual("invalid_authentication"); }); }); diff --git a/server/emails/mailer.tsx b/server/emails/mailer.tsx index 0c6517a38c..a6a218b88d 100644 --- a/server/emails/mailer.tsx +++ b/server/emails/mailer.tsx @@ -3,6 +3,7 @@ import type { Transporter } from "nodemailer"; import nodemailer from "nodemailer"; import type SMTPTransport from "nodemailer/lib/smtp-transport"; import Oy from "oy-vey"; +import { toError } from "@shared/utils/error"; import env from "@server/env"; import { InternalError } from "@server/errors"; import Logger from "@server/logging/Logger"; @@ -216,7 +217,7 @@ export class Mailer { ); } } catch (err) { - Logger.error(`Error sending email to ${data.to}`, err); + Logger.error(`Error sending email to ${data.to}`, toError(err)); throw err; // Re-throw for queue to re-try } }; diff --git a/server/emails/templates/BaseEmail.tsx b/server/emails/templates/BaseEmail.tsx index 03fa1b3a3a..0d1bbe0fe2 100644 --- a/server/emails/templates/BaseEmail.tsx +++ b/server/emails/templates/BaseEmail.tsx @@ -5,6 +5,7 @@ import invariant from "invariant"; import { t as i18nT } from "i18next"; import { subMinutes } from "date-fns"; import type { Node } from "prosemirror-model"; +import { toError } from "@shared/utils/error"; import { randomString } from "@shared/random"; import { TeamPreference } from "@shared/types"; import { unicodeCLDRtoBCP47 } from "@shared/utils/date"; @@ -194,7 +195,11 @@ export default abstract class BaseEmail< notification.emailedAt = new Date(); await notification.save(); } catch (err) { - Logger.error(`Failed to update notification`, err, this.metadata); + Logger.error( + `Failed to update notification`, + toError(err), + this.metadata + ); } } } diff --git a/server/index.ts b/server/index.ts index 549244b1a5..f7a2c0f708 100644 --- a/server/index.ts +++ b/server/index.ts @@ -1,5 +1,6 @@ /* oxlint-disable @typescript-eslint/no-misused-promises */ /* oxlint-disable import/order */ +import { toError } from "@shared/utils/error"; import env from "./env"; import "./logging/tracer"; // must come before importing any instrumented module @@ -159,7 +160,7 @@ async function start(_id: number, disconnect: () => void) { try { await sequelize.query("SELECT 1"); } catch (err) { - Logger.error("Database connection failed", err); + Logger.error("Database connection failed", toError(err)); ctx.status = 500; return; } @@ -167,7 +168,7 @@ async function start(_id: number, disconnect: () => void) { try { await Redis.defaultClient.ping(); } catch (err) { - Logger.error("Redis ping failed", err); + Logger.error("Redis ping failed", toError(err)); ctx.status = 500; return; } diff --git a/server/middlewares/apexAuthRedirect.ts b/server/middlewares/apexAuthRedirect.ts index 44d2ccf3c9..466a9963f6 100644 --- a/server/middlewares/apexAuthRedirect.ts +++ b/server/middlewares/apexAuthRedirect.ts @@ -1,4 +1,5 @@ import type { Next } from "koa"; +import { toError } from "@shared/utils/error"; import { parseDomain } from "@shared/utils/domains"; import Logger from "@server/logging/Logger"; import { Team } from "@server/models"; @@ -49,7 +50,7 @@ export default function apexAuthRedirect({ ? ctx.redirect("/") : ctx.redirectOnClient(getRedirectPath(ctx, team)); } catch (err) { - Logger.error("Error fetching team", err); + Logger.error("Error fetching team", toError(err)); return ctx.redirect(getErrorPath(ctx)); } } else { diff --git a/server/middlewares/authentication.test.ts b/server/middlewares/authentication.test.ts index fc4608cdfe..1e9d631bce 100644 --- a/server/middlewares/authentication.test.ts +++ b/server/middlewares/authentication.test.ts @@ -1,4 +1,5 @@ import type { DefaultState } from "koa"; +import { errToString } from "@shared/utils/error"; import { randomString } from "@shared/random"; import { Scope } from "@shared/types"; import { @@ -49,7 +50,7 @@ describe("Authentication middleware", () => { vi.fn() ); } catch (e) { - expect(e.message).toBe("Invalid token"); + expect(errToString(e)).toBe("Invalid token"); } }); @@ -73,7 +74,7 @@ describe("Authentication middleware", () => { vi.fn() ); } catch (e) { - expect(e.message).toBe("Invalid authentication type"); + expect(errToString(e)).toBe("Invalid authentication type"); } }); }); @@ -147,9 +148,11 @@ describe("Authentication middleware", () => { ); throw new Error("Expected error to be thrown"); } catch (e) { - expect(e.status).toBe(403); - expect(e.id).toBe("authorization_error"); - expect(e.message).toContain("does not have access to this resource"); + expect(e).toHaveProperty("status", 403); + expect(e).toHaveProperty("id", "authorization_error"); + expect(errToString(e)).toContain( + "does not have access to this resource" + ); } }); @@ -170,7 +173,7 @@ describe("Authentication middleware", () => { vi.fn() ); } catch (e) { - expect(e.message).toBe("Invalid API key"); + expect(errToString(e)).toBe("Invalid API key"); } }); }); @@ -225,7 +228,9 @@ describe("Authentication middleware", () => { vi.fn() ); } catch (e) { - expect(e.message).toContain("does not have access to this resource"); + expect(errToString(e)).toContain( + "does not have access to this resource" + ); } }); @@ -255,7 +260,7 @@ describe("Authentication middleware", () => { vi.fn() ); } catch (e) { - expect(e.message).toContain( + expect(errToString(e)).toContain( "must be passed in the Authorization header" ); } @@ -279,7 +284,7 @@ describe("Authentication middleware", () => { vi.fn() ); } catch (e) { - expect(e.message).toBe( + expect(errToString(e)).toBe( 'Bad Authorization header format. Format is "Authorization: Bearer "' ); } @@ -353,10 +358,10 @@ describe("Authentication middleware", () => { error = err; } - expect(error.message).toEqual( + expect(errToString(error)).toEqual( "Your access has been suspended by a workspace admin" ); - expect(error.errorData.adminEmail).toEqual(admin.email); + expect(error).toHaveProperty("errorData.adminEmail", admin.email); }); it("should return an error for deleted team", async () => { @@ -383,6 +388,6 @@ describe("Authentication middleware", () => { error = err; } - expect(error.message).toEqual("Invalid token"); + expect(errToString(error)).toEqual("Invalid token"); }); }); diff --git a/server/middlewares/rateLimiter.ts b/server/middlewares/rateLimiter.ts index dca5b10980..122f7d814c 100644 --- a/server/middlewares/rateLimiter.ts +++ b/server/middlewares/rateLimiter.ts @@ -1,5 +1,7 @@ import type { Next } from "koa"; import { defaults } from "es-toolkit/compat"; +import { RateLimiterRes } from "rate-limiter-flexible"; +import { toError } from "@shared/utils/error"; import env from "@server/env"; import { RateLimitExceededError } from "@server/errors"; import Logger from "@server/logging/Logger"; @@ -69,8 +71,11 @@ export function defaultRateLimiter() { try { await limiter.consume(key); } catch (rateLimiterRes) { - if (rateLimiterRes instanceof Error) { - Logger.error("Rate limiter error", rateLimiterRes); + if ( + rateLimiterRes instanceof Error || + !(rateLimiterRes instanceof RateLimiterRes) + ) { + Logger.error("Rate limiter error", toError(rateLimiterRes)); return next(); } diff --git a/server/middlewares/validate.ts b/server/middlewares/validate.ts index b44bb08695..b013d7976d 100644 --- a/server/middlewares/validate.ts +++ b/server/middlewares/validate.ts @@ -1,6 +1,7 @@ import type { Next } from "koa"; import type { z } from "zod"; import { ZodError } from "zod"; +import { toError } from "@shared/utils/error"; import { ValidationError } from "@server/errors"; import type { APIContext } from "@server/types"; @@ -22,7 +23,7 @@ export default function validate>>( : message; throw ValidationError(errMessage); } - ctx.throw(err); + ctx.throw(toError(err)); } return next(); }; diff --git a/server/models/Attachment.ts b/server/models/Attachment.ts index 224428d243..4a76a398f4 100644 --- a/server/models/Attachment.ts +++ b/server/models/Attachment.ts @@ -21,6 +21,7 @@ import { BeforeCreate, BeforeUpdate, } from "sequelize-typescript"; +import { errToString } from "@shared/utils/error"; import { ValidationError } from "@server/errors"; import FileStorage from "@server/storage/files"; import { ValidateKey } from "@server/validation"; @@ -183,7 +184,7 @@ class Attachment extends IdModel< { id: model.id, teamId: model.teamId, - message: err.message, + message: errToString(err), } ); } diff --git a/server/models/Collection.ts b/server/models/Collection.ts index 64d121a081..ea4769c080 100644 --- a/server/models/Collection.ts +++ b/server/models/Collection.ts @@ -855,7 +855,7 @@ class Collection extends ParanoidModel< return this; }; - deleteDocument = async function (document: Document, options?: FindOptions) { + deleteDocument = async (document: Document, options?: FindOptions) => { await this.removeDocumentInStructure(document, options); // Helper to destroy all child documents for a document @@ -879,12 +879,12 @@ class Collection extends ParanoidModel< await document.destroy(options); }; - removeDocumentInStructure = async function ( + removeDocumentInStructure = async ( document: Document, options?: FindOptions & { save?: boolean; } - ) { + ) => { if (!this.documentStructure) { return; } @@ -942,7 +942,7 @@ class Collection extends ParanoidModel< return result; }; - getDocumentParents = function (documentId: string): string[] | void { + getDocumentParents = (documentId: string): string[] | void => { let result!: string[]; const loopChildren = (documents: NavigationNode[], path: string[] = []) => { @@ -969,10 +969,10 @@ class Collection extends ParanoidModel< /** * Update document's title and url in the documentStructure */ - updateDocument = async function ( + updateDocument = async ( updatedDocument: Document, options?: { transaction?: Transaction | null | undefined } - ) { + ) => { if (!this.documentStructure) { return; } @@ -1007,7 +1007,7 @@ class Collection extends ParanoidModel< return this; }; - addDocumentToStructure = async function ( + addDocumentToStructure = async ( document: Document, index?: number, options: FindOptions & { @@ -1017,7 +1017,7 @@ class Collection extends ParanoidModel< includeArchived?: boolean; insertOrder?: "prepend" | "append"; } = {} - ) { + ) => { if (!this.documentStructure) { this.documentStructure = []; } diff --git a/server/models/FileOperation.ts b/server/models/FileOperation.ts index 101df621c7..08b5ca9553 100644 --- a/server/models/FileOperation.ts +++ b/server/models/FileOperation.ts @@ -91,12 +91,12 @@ class FileOperation extends ParanoidModel< /** * Mark the current file operation as expired and remove the file from storage. */ - expire = async function () { + expire = async () => { this.state = FileOperationState.Expired; try { await FileStorage.deleteFile(this.key); } catch (err) { - if (err.retryable) { + if (err instanceof Error && "retryable" in err && err.retryable) { throw err; } } diff --git a/server/models/Group.ts b/server/models/Group.ts index f57b19fa9f..83761b8924 100644 --- a/server/models/Group.ts +++ b/server/models/Group.ts @@ -39,7 +39,7 @@ import NotContainsUrl from "./validators/NotContainsUrl"; tableName: "groups", modelName: "group", validate: { - async isUniqueNameInTeam() { + async isUniqueNameInTeam(this: Group) { const foundItem = await Group.findOne({ where: { teamId: this.teamId, diff --git a/server/models/IntegrationAuthentication.ts b/server/models/IntegrationAuthentication.ts index 01c2058504..c19aa3e56e 100644 --- a/server/models/IntegrationAuthentication.ts +++ b/server/models/IntegrationAuthentication.ts @@ -10,6 +10,7 @@ import { BelongsTo, Column, } from "sequelize-typescript"; +import { toError } from "@shared/utils/error"; import type { IntegrationService } from "@shared/types"; import Logger from "../logging/Logger"; import Team from "./Team"; @@ -161,7 +162,10 @@ class IntegrationAuthentication extends IdModel< return refreshedToken; } catch (err) { - Logger.warn(`Failed to refresh ${this.service} access token`, err); + Logger.warn( + `Failed to refresh ${this.service} access token`, + toError(err) + ); // Continue with existing token - it might still work return this.token; } diff --git a/server/models/Team.ts b/server/models/Team.ts index 6733ce0024..0147507cca 100644 --- a/server/models/Team.ts +++ b/server/models/Team.ts @@ -408,7 +408,7 @@ class Team extends ParanoidModel< }); }; - public collectionIds = async function (paranoid = true) { + public collectionIds = async (paranoid = true) => { const models = await Collection.findAll({ attributes: ["id"], where: { diff --git a/server/models/User.test.ts b/server/models/User.test.ts index 410a29406e..ec372570f1 100644 --- a/server/models/User.test.ts +++ b/server/models/User.test.ts @@ -1,4 +1,5 @@ import { faker } from "@faker-js/faker"; +import { errToString } from "@shared/utils/error"; import { CollectionPermission, UserRole } from "@shared/types"; import { createContext } from "@server/context"; import { Event } from "@server/models"; @@ -123,7 +124,7 @@ describe("user model", () => { error = err; } - expect(error && error.message).toContain("Cannot delete last user"); + expect(errToString(error)).toContain("Cannot delete last user"); }); it("should prevent last admin from deleting account", async () => { @@ -139,7 +140,7 @@ describe("user model", () => { error = err; } - expect(error && error.message).toContain("Cannot delete account"); + expect(errToString(error)).toContain("Cannot delete account"); }); it("should not prevent multiple admin from deleting account", async () => { diff --git a/server/models/User.ts b/server/models/User.ts index 8234c36658..328894c892 100644 --- a/server/models/User.ts +++ b/server/models/User.ts @@ -935,7 +935,11 @@ class User extends ParanoidModel< } }; - static findByEmail = async function (ctx: APIContext, email: string) { + static findByEmail = async function ( + this: typeof User, + ctx: APIContext, + email: string + ) { return this.findOne({ where: { teamId: ctx.state.auth.user.teamId, @@ -945,7 +949,7 @@ class User extends ParanoidModel< }); }; - static getCounts = async function (teamId: string) { + static getCounts = async function (this: typeof User, teamId: string) { const countSql = ` SELECT COUNT(CASE WHEN "suspendedAt" IS NOT NULL THEN 1 END) as "suspendedCount", @@ -958,7 +962,14 @@ class User extends ParanoidModel< WHERE "deletedAt" IS NULL AND "teamId" = :teamId `; - const [results] = await this.sequelize.query(countSql, { + const [counts] = await this.sequelize!.query<{ + activeCount: string; + adminCount: string; + invitedCount: string; + suspendedCount: string; + viewerCount: string; + count: string; + }>(countSql, { type: QueryTypes.SELECT, replacements: { teamId, @@ -967,15 +978,6 @@ class User extends ParanoidModel< }, }); - const counts: { - activeCount: string; - adminCount: string; - invitedCount: string; - suspendedCount: string; - viewerCount: string; - count: string; - } = results; - return { active: parseInt(counts.activeCount), admins: parseInt(counts.adminCount), diff --git a/server/models/UserAuthentication.ts b/server/models/UserAuthentication.ts index 3ce1721092..fa9d588864 100644 --- a/server/models/UserAuthentication.ts +++ b/server/models/UserAuthentication.ts @@ -124,7 +124,11 @@ class UserAuthentication extends IdModel< return true; } catch (error) { - if (error.id === "authentication_required") { + if ( + error instanceof Error && + "id" in error && + error.id === "authentication_required" + ) { return false; } diff --git a/server/models/decorators/Encrypted.ts b/server/models/decorators/Encrypted.ts index 3535b1e25f..3174db87db 100644 --- a/server/models/decorators/Encrypted.ts +++ b/server/models/decorators/Encrypted.ts @@ -1,5 +1,6 @@ import { isEmpty, isNil } from "es-toolkit/compat"; import { getAttributes } from "sequelize-typescript"; +import { toError, errToString } from "@shared/utils/error"; import Logger from "@server/logging/Logger"; import vaults from "@server/storage/vaults"; @@ -41,13 +42,14 @@ export default function Encrypted(target: object, propertyKey: string) { ? defaultValue : value; } catch (err) { - if (err.message.includes("Unexpected end of JSON input")) { + const message = errToString(err); + if (message.includes("Unexpected end of JSON input")) { return defaultValue; } - if (err.message.includes("bad decrypt")) { + if (message.includes("bad decrypt")) { Logger.fatal( `Failed to decrypt database column (${propertyKey}). The SECRET_KEY environment variable may have changed since installation.`, - err + toError(err) ); } throw err; @@ -61,7 +63,10 @@ export default function Encrypted(target: object, propertyKey: string) { Reflect.getMetadata(key, this, propertyKey).set.call(this, value); } } catch (err) { - if (err.message.includes("Invalid key length")) { + if ( + err instanceof Error && + err.message.includes("Invalid key length") + ) { Logger.fatal( `Failed to encrypt database column (${propertyKey}). The SECRET_KEY environment variable is not the correct length.`, err diff --git a/server/models/helpers/ProsemirrorHelper.tsx b/server/models/helpers/ProsemirrorHelper.tsx index f37bf85898..25335203f0 100644 --- a/server/models/helpers/ProsemirrorHelper.tsx +++ b/server/models/helpers/ProsemirrorHelper.tsx @@ -16,6 +16,7 @@ import { yDocToProsemirrorJSON, } from "y-prosemirror"; import * as Y from "yjs"; +import { toError, errToString } from "@shared/utils/error"; import Diff from "@shared/editor/extensions/Diff"; import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper"; import type { ExtendedChange } from "@shared/editor/lib/ChangesetHelper"; @@ -532,7 +533,10 @@ export class ProsemirrorHelper extends SharedProsemirrorHelper { ); styleTags = sheet.getStyleTags(); } catch (error) { - Logger.error("Failed to render styles on node HTML conversion", error); + Logger.error( + "Failed to render styles on node HTML conversion", + toError(error) + ); } finally { sheet.seal(); } @@ -671,7 +675,7 @@ export class ProsemirrorHelper extends SharedProsemirrorHelper { try { view?.destroy(); } catch (err) { - Logger.error("Error destroying ProseMirror view", err); + Logger.error("Error destroying ProseMirror view", toError(err)); } cleanupEnv?.(); } @@ -990,7 +994,7 @@ export class ProsemirrorHelper extends SharedProsemirrorHelper { } } catch (err) { Logger.warn("Failed to download image for attachment", { - error: err.message, + error: errToString(err), src, }); } diff --git a/server/models/helpers/TextHelper.ts b/server/models/helpers/TextHelper.ts index d995b3cd33..ca21907758 100644 --- a/server/models/helpers/TextHelper.ts +++ b/server/models/helpers/TextHelper.ts @@ -1,4 +1,5 @@ import { chunk, escapeRegExp } from "es-toolkit/compat"; +import { errToString } from "@shared/utils/error"; import { AttachmentPreset } from "@shared/types"; import { isInternalUrl } from "@shared/utils/urls"; import attachmentCreator from "@server/commands/attachmentCreator"; @@ -117,7 +118,7 @@ export class TextHelper { } } catch (err) { Logger.warn("Failed to download image for attachment", { - error: err.message, + error: errToString(err), src: image.src, }); } diff --git a/server/onerror.ts b/server/onerror.ts index 00ba281ab0..1ddfd52507 100644 --- a/server/onerror.ts +++ b/server/onerror.ts @@ -7,12 +7,13 @@ import { escape, isNil, snakeCase } from "es-toolkit/compat"; import env from "@server/env"; import { ClientClosedRequestError, InternalError } from "@server/errors"; import { requestErrorHandler } from "@server/logging/sentry"; +import type { AppContext } from "@server/types"; let errorHtmlCache: Buffer | undefined; export default function onerror(app: Koa) { // oxlint-disable-next-line @typescript-eslint/no-explicit-any - app.context.onerror = function (err: any) { + app.context.onerror = function (this: AppContext, err: any) { // Don't do anything if there is no error, this allows you to pass `this.onerror` to node-style callbacks. if (isNil(err)) { return; diff --git a/server/queues/tasks/APIImportTask.ts b/server/queues/tasks/APIImportTask.ts index 5740912abb..e2037b7793 100644 --- a/server/queues/tasks/APIImportTask.ts +++ b/server/queues/tasks/APIImportTask.ts @@ -20,6 +20,7 @@ import { ImportTaskPhase, ImportTaskState, } from "@shared/types"; +import { toError } from "@shared/utils/error"; import { createContext } from "@server/context"; import { schema } from "@server/editor"; import Logger from "@server/logging/Logger"; @@ -410,7 +411,7 @@ export default abstract class APIImportTask< // upload attachments failure is not critical enough to fail the whole import. Logger.error( `upload attachment task failed for externalId ${externalId}`, - err + toError(err) ); } diff --git a/server/queues/tasks/DocumentImportTask.ts b/server/queues/tasks/DocumentImportTask.ts index c5f0ed1d3a..6043e7379b 100644 --- a/server/queues/tasks/DocumentImportTask.ts +++ b/server/queues/tasks/DocumentImportTask.ts @@ -1,3 +1,4 @@ +import { errToString } from "@shared/utils/error"; import type { SourceMetadata } from "@shared/types"; import documentCreator from "@server/commands/documentCreator"; import documentImporter from "@server/commands/documentImporter"; @@ -73,7 +74,7 @@ export default class DocumentImportTask extends BaseTask { ); return { documentId: document.id }; } catch (err) { - return { error: err.message }; + return { error: errToString(err) }; } finally { await FileStorage.deleteFile(key); } diff --git a/server/queues/tasks/ExportDocumentTreeTask.ts b/server/queues/tasks/ExportDocumentTreeTask.ts index 4c09cdfda3..bc8574cc17 100644 --- a/server/queues/tasks/ExportDocumentTreeTask.ts +++ b/server/queues/tasks/ExportDocumentTreeTask.ts @@ -1,6 +1,7 @@ import path from "node:path"; import { escapeRegExp } from "es-toolkit/compat"; import type { ZipFile } from "yazl"; +import { errToString } from "@shared/utils/error"; import type { NavigationNode } from "@shared/types"; import { FileOperationFormat } from "@shared/types"; import Logger from "@server/logging/Logger"; @@ -89,7 +90,7 @@ export default abstract class ExportDocumentTreeTask extends ExportTask { Logger.warn(`Failed to read attachment from storage`, { attachmentId: attachment.id, teamId: attachment.teamId, - error: err.message, + error: errToString(err), }); buffer = Buffer.from(""); } diff --git a/server/queues/tasks/ExportJSONTask.ts b/server/queues/tasks/ExportJSONTask.ts index 685c989fd0..50b6feed4a 100644 --- a/server/queues/tasks/ExportJSONTask.ts +++ b/server/queues/tasks/ExportJSONTask.ts @@ -1,5 +1,6 @@ import { ZipFile } from "yazl"; import { omit } from "es-toolkit/compat"; +import { errToString } from "@shared/utils/error"; import type { NavigationNode } from "@shared/types"; import env from "@server/env"; import Logger from "@server/logging/Logger"; @@ -95,7 +96,7 @@ export default class ExportJSONTask extends ExportTask { Logger.warn(`Failed to read attachment from storage`, { attachmentId: attachment.id, teamId: attachment.teamId, - error: err.message, + error: errToString(err), }); buffer = Buffer.from(""); } diff --git a/server/queues/tasks/ExportTask.ts b/server/queues/tasks/ExportTask.ts index 7d87be51f7..c3d5c05a3b 100644 --- a/server/queues/tasks/ExportTask.ts +++ b/server/queues/tasks/ExportTask.ts @@ -1,5 +1,6 @@ import fs from "fs-extra"; import { truncate } from "es-toolkit/compat"; +import { toError } from "@shared/utils/error"; import type { NavigationNode } from "@shared/types"; import { FileOperationState, NotificationEventType } from "@shared/types"; import { bytesToHumanReadable } from "@shared/utils/files"; @@ -93,7 +94,7 @@ export default abstract class ExportTask extends BaseTask { } catch (error) { await this.updateFileOperation(fileOperation, { state: FileOperationState.Error, - error, + error: toError(error), }); if (user.subscribedToEventType(NotificationEventType.ExportCompleted)) { await new ExportFailureEmail({ @@ -223,7 +224,7 @@ export default abstract class ExportTask extends BaseTask { */ private async updateFileOperation( fileOperation: FileOperation, - options: Partial & { error?: Error } + options: Omit, "error"> & { error?: Error } ) { await fileOperation.update( { diff --git a/server/queues/tasks/ImportTask.ts b/server/queues/tasks/ImportTask.ts index 61d3efaabe..ca8a33d3c7 100644 --- a/server/queues/tasks/ImportTask.ts +++ b/server/queues/tasks/ImportTask.ts @@ -3,6 +3,7 @@ import fs from "fs-extra"; import { chunk, truncate } from "es-toolkit/compat"; import type { InferCreationAttributes } from "sequelize"; import tmp from "tmp"; +import { toError } from "@shared/utils/error"; import type { CollectionSort, ProsemirrorData } from "@shared/types"; import { AttachmentPreset, @@ -150,7 +151,7 @@ export default abstract class ImportTask extends BaseTask { } catch (error) { Logger.error( `ImportTask failed to persist data for ${fileOperationId}`, - error + toError(error) ); throw new Error("Sorry, an internal error occurred during import"); } @@ -162,12 +163,12 @@ export default abstract class ImportTask extends BaseTask { return result; } catch (error) { - Logger.error(`ImportTask failed for ${fileOperationId}`, error); + Logger.error(`ImportTask failed for ${fileOperationId}`, toError(error)); await this.updateFileOperation( fileOperation, FileOperationState.Error, - error + toError(error) ); throw error; } finally { @@ -269,7 +270,7 @@ export default abstract class ImportTask extends BaseTask { } catch (error) { Logger.error( `ImportTask failed to cleanup extracted data for ${fileOperation.id}`, - error + toError(error) ); } } diff --git a/server/queues/tasks/UpdateDocumentsPopularityScoreTask.ts b/server/queues/tasks/UpdateDocumentsPopularityScoreTask.ts index 33fc305f5b..59c3fe7a50 100644 --- a/server/queues/tasks/UpdateDocumentsPopularityScoreTask.ts +++ b/server/queues/tasks/UpdateDocumentsPopularityScoreTask.ts @@ -2,6 +2,7 @@ import crypto from "node:crypto"; import { setTimeout } from "node:timers/promises"; import { subDays } from "date-fns"; import { QueryTypes } from "sequelize"; +import { toError } from "@shared/utils/error"; import { Minute } from "@shared/utils/time"; import env from "@server/env"; import Logger from "@server/logging/Logger"; @@ -128,7 +129,10 @@ export default class UpdateDocumentsPopularityScoreTask extends CronTask { } } catch (error) { totalErrors++; - Logger.error(`Batch ${batchNumber} failed after retries`, error); + Logger.error( + `Batch ${batchNumber} failed after retries`, + toError(error) + ); // Remove failed batch from working table to prevent infinite loop await this.skipCurrentBatch(); @@ -140,7 +144,10 @@ export default class UpdateDocumentsPopularityScoreTask extends CronTask { `Completed updating popularity scores: ${totalUpdated} documents updated, ${totalErrors} batch errors` ); } catch (error) { - Logger.error("Failed to update document popularity scores", error); + Logger.error( + "Failed to update document popularity scores", + toError(error) + ); throw error; } finally { // Always clean up the working table diff --git a/server/queues/tasks/UploadAttachmentFromUrlTask.ts b/server/queues/tasks/UploadAttachmentFromUrlTask.ts index 5c7c18a1df..dcd4fe2ecc 100644 --- a/server/queues/tasks/UploadAttachmentFromUrlTask.ts +++ b/server/queues/tasks/UploadAttachmentFromUrlTask.ts @@ -1,3 +1,4 @@ +import { errToString } from "@shared/utils/error"; import { createContext } from "@server/context"; import { Attachment } from "@server/models"; import FileStorage from "@server/storage/files"; @@ -39,7 +40,7 @@ export default class UploadAttachmentFromUrlTask extends BaseTask { }); } } catch (err) { - return { error: err.message }; + return { error: errToString(err) }; } return {}; diff --git a/server/queues/tasks/UploadAttachmentsForImportTask.ts b/server/queues/tasks/UploadAttachmentsForImportTask.ts index 3cc52b85aa..5e90ff8b7a 100644 --- a/server/queues/tasks/UploadAttachmentsForImportTask.ts +++ b/server/queues/tasks/UploadAttachmentsForImportTask.ts @@ -1,4 +1,5 @@ import { Sema } from "async-sema"; +import { toError } from "@shared/utils/error"; import Logger from "@server/logging/Logger"; import { Attachment } from "@server/models"; import FileStorage from "@server/storage/files"; @@ -54,7 +55,7 @@ export default class UploadAttachmentsForImportTask extends BaseTask { }); } } catch (err) { - Logger.error("error uploading attachments for import", err); + Logger.error("error uploading attachments for import", toError(err)); throw err; } finally { sema.release(); diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index 91411068f8..b1354736d1 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -9,6 +9,7 @@ import mime from "mime-types"; import type { Order, ScopeOptions, WhereOptions } from "sequelize"; import { Op, Sequelize } from "sequelize"; import { randomUUID } from "node:crypto"; +import { errToString } from "@shared/utils/error"; import type { DirectionFilter, SortFilter } from "@shared/types"; import { type NavigationNode } from "@shared/types"; import { @@ -932,7 +933,7 @@ router.post( Logger.warn(`Failed to read attachment from storage`, { attachmentId: attachment.id, teamId: attachment.teamId, - error: err.message, + error: errToString(err), }); buffer = Buffer.from(""); } diff --git a/server/routes/api/middlewares/apiErrorHandler.ts b/server/routes/api/middlewares/apiErrorHandler.ts index 0b621c7cf9..0221f80e1c 100644 --- a/server/routes/api/middlewares/apiErrorHandler.ts +++ b/server/routes/api/middlewares/apiErrorHandler.ts @@ -18,6 +18,7 @@ export default function apiErrorHandler() { if ( !(err instanceof AuthorizationError) && + err instanceof Error && /Authorization error/i.test(err.message) ) { transformedErr = AuthorizationError(); @@ -34,9 +35,9 @@ export default function apiErrorHandler() { } if ( - err.code === "ENOENT" || + (err instanceof Error && "code" in err && err.code === "ENOENT") || err instanceof SequelizeEmptyResultError || - /Not found/i.test(err.message) + (err instanceof Error && /Not found/i.test(err.message)) ) { transformedErr = NotFoundError(); } diff --git a/server/routes/api/revisions/revisions.ts b/server/routes/api/revisions/revisions.ts index 08f73afb5b..954265ea20 100644 --- a/server/routes/api/revisions/revisions.ts +++ b/server/routes/api/revisions/revisions.ts @@ -3,6 +3,7 @@ import Router from "koa-router"; import contentDisposition from "content-disposition"; import { escapeRegExp } from "es-toolkit/compat"; import mime from "mime-types"; +import { errToString } from "@shared/utils/error"; import { UserRole } from "@shared/types"; import { RevisionHelper } from "@shared/utils/RevisionHelper"; import slugify from "@shared/utils/slugify"; @@ -207,7 +208,7 @@ router.post( Logger.warn(`Failed to read attachment from storage`, { attachmentId: attachment.id, teamId: attachment.teamId, - error: err.message, + error: errToString(err), }); buffer = Buffer.from(""); } diff --git a/server/routes/api/shares/shares.ts b/server/routes/api/shares/shares.ts index c4a3e94194..f8b9f38644 100644 --- a/server/routes/api/shares/shares.ts +++ b/server/routes/api/shares/shares.ts @@ -139,7 +139,7 @@ router.post( policies: presentPolicies(user, shares), }; } catch (err) { - if (err.id === "not_found") { + if (err instanceof Error && "id" in err && err.id === "not_found") { ctx.response.status = 204; return; } diff --git a/server/routes/api/urls/urls.ts b/server/routes/api/urls/urls.ts index 93b5ead181..5ed0619a92 100644 --- a/server/routes/api/urls/urls.ts +++ b/server/routes/api/urls/urls.ts @@ -278,7 +278,7 @@ router.post( }); }); } catch (err) { - if (err.code === "ENOTFOUND") { + if (err instanceof Error && "code" in err && err.code === "ENOTFOUND") { throw NotFoundError("No CNAME record found"); } diff --git a/server/routes/index.ts b/server/routes/index.ts index 4beb87e3fb..ccd300d1b2 100644 --- a/server/routes/index.ts +++ b/server/routes/index.ts @@ -39,7 +39,7 @@ router.use(["/images/*", "/email/*", "/fonts/*"], async (ctx, next) => { }, }); } catch (err) { - if (err.status !== 404) { + if (!(err instanceof Error && "status" in err && err.status === 404)) { throw err; } } @@ -78,7 +78,7 @@ if (env.isProduction) { }, }); } catch (err) { - if (err.status === 404) { + if (err instanceof Error && "status" in err && err.status === 404) { // Serve a bad request instead of not found if the file doesn't exist // This prevents CDN's from caching the response, allowing them to continue // serving old file versions diff --git a/server/routes/mcp/index.ts b/server/routes/mcp/index.ts index 3adbe198c1..e330b8f1b4 100644 --- a/server/routes/mcp/index.ts +++ b/server/routes/mcp/index.ts @@ -5,6 +5,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js"; import { ErrorCode } from "@modelcontextprotocol/sdk/types.js"; +import { toError } from "@shared/utils/error"; import { TeamPreference } from "@shared/types"; import { NotFoundError } from "@server/errors"; import Logger from "@server/logging/Logger"; @@ -126,7 +127,7 @@ router.post( } catch (error) { Logger.error( "MCP request handling failed", - error instanceof Error ? error : new Error(String(error)), + toError(error), undefined, ctx.req ); diff --git a/server/routes/oauth/middlewares/oauthErrorHandler.ts b/server/routes/oauth/middlewares/oauthErrorHandler.ts index 308dd5bb61..5994c2618f 100644 --- a/server/routes/oauth/middlewares/oauthErrorHandler.ts +++ b/server/routes/oauth/middlewares/oauthErrorHandler.ts @@ -3,6 +3,23 @@ import { ValidationError as SequelizeValidationError, EmptyResultError as SequelizeEmptyResultError, } from "sequelize"; +import { errToString } from "@shared/utils/error"; + +/** Extract the first numeric status-like property from an unknown error. */ +function statusCodeFromError(err: unknown): number { + if (err instanceof Error) { + if ("status" in err && typeof err.status === "number") { + return err.status; + } + if ("statusCode" in err && typeof err.statusCode === "number") { + return err.statusCode; + } + if ("code" in err && typeof err.code === "number") { + return err.code; + } + } + return 500; +} /** * To adhere to the OAuth 2.0 specification, errors from the /token and /authorize routes @@ -31,7 +48,7 @@ export default function oauthErrorHandler() { return; } - ctx.status = err.status || err.statusCode || err.code || 500; + ctx.status = statusCodeFromError(err); // Map common HTTP status codes to OAuth error types let errorType = "server_error"; if (ctx.status === 400) { @@ -42,7 +59,7 @@ export default function oauthErrorHandler() { ctx.body = { error: errorType, - error_description: err.message, + error_description: errToString(err), }; } }; diff --git a/server/services/websockets.ts b/server/services/websockets.ts index 5cfac37391..c11c80234e 100644 --- a/server/services/websockets.ts +++ b/server/services/websockets.ts @@ -5,6 +5,7 @@ import cookie from "cookie"; import type Koa from "koa"; import IO from "socket.io"; import { createAdapter } from "socket.io-redis"; +import { errToString } from "@shared/utils/error"; import env from "@server/env"; import { AuthenticationError } from "@server/errors"; import Logger from "@server/logging/Logger"; @@ -133,10 +134,11 @@ export default function init( socket.emit("authenticated", true); void authenticated(io, socket); } catch (err) { + const message = errToString(err); Logger.debug("websockets", `Authentication error socket ${socket.id}`, { - error: err.message, + error: message, }); - socket.emit("unauthorized", { message: err.message }, function () { + socket.emit("unauthorized", { message }, function () { socket.disconnect(); }); } diff --git a/server/services/worker.ts b/server/services/worker.ts index 9d58ace917..2960a0076d 100644 --- a/server/services/worker.ts +++ b/server/services/worker.ts @@ -1,3 +1,4 @@ +import { toError } from "@shared/utils/error"; import env from "@server/env"; import Logger from "@server/logging/Logger"; import { setResource, addTags } from "@server/logging/tracer"; @@ -69,7 +70,7 @@ export default async function init() { } catch (error) { Logger.error( `Error adding ${event.name} to ${name} queue`, - error, + toError(error), event ); err = error; @@ -125,7 +126,7 @@ export default async function init() { Logger.error( `Error processing ${event.name} in ${name}`, - err, + toError(err), event ); throw err; @@ -171,7 +172,7 @@ export default async function init() { await task.onFailed(props).catch(); // suppress exception from 'onFailed'. } - Logger.error(`Error processing task in ${name}`, err, props); + Logger.error(`Error processing task in ${name}`, toError(err), props); throw err; } }) diff --git a/server/storage/database.ts b/server/storage/database.ts index 4e25661319..f246db16d3 100644 --- a/server/storage/database.ts +++ b/server/storage/database.ts @@ -11,6 +11,7 @@ import type { SequelizeOptions } from "sequelize-typescript"; import { Sequelize } from "sequelize-typescript"; import type { MigrationError } from "umzug"; import { Umzug, SequelizeStorage } from "umzug"; +import { toError } from "@shared/utils/error"; import env from "@server/env"; import { ClientClosedRequestError } from "@server/errors"; import type Model from "@server/models/base/Model"; @@ -196,13 +197,16 @@ export const checkConnection = async (db: Sequelize) => { try { await db.authenticate(); } catch (error) { - if (error.message.includes("does not support SSL")) { + if ( + error instanceof Error && + error.message.includes("does not support SSL") + ) { Logger.fatal( "The database does not support SSL connections. Set the `PGSSLMODE` environment variable to `disable` or enable SSL on your database server.", error ); } else { - Logger.fatal("Failed to connect to database", error); + Logger.fatal("Failed to connect to database", toError(error)); } } }; diff --git a/server/storage/files/BaseStorage.ts b/server/storage/files/BaseStorage.ts index fb354d2b61..0fe1d215e8 100644 --- a/server/storage/files/BaseStorage.ts +++ b/server/storage/files/BaseStorage.ts @@ -2,6 +2,7 @@ import type { Blob } from "node:buffer"; import type { Readable } from "node:stream"; import type { PresignedPost } from "@aws-sdk/s3-presigned-post"; import { omit } from "es-toolkit/compat"; +import { toError, errToString } from "@shared/utils/error"; import FileHelper from "@shared/editor/lib/FileHelper"; import { isBase64Url, isInternalUrl } from "@shared/utils/urls"; import { Week } from "@shared/utils/time"; @@ -217,7 +218,7 @@ export default abstract class BaseStorage { res.headers.get("content-type") ?? "application/octet-stream"; } catch (err) { Logger.warn("Error fetching URL to upload", { - error: err.message, + error: errToString(err), url, key, acl, @@ -247,7 +248,7 @@ export default abstract class BaseStorage { } : undefined; } catch (err) { - Logger.error("Error uploading to file storage from URL", err, { + Logger.error("Error uploading to file storage from URL", toError(err), { url, key, acl, diff --git a/server/storage/files/LocalStorage.ts b/server/storage/files/LocalStorage.ts index 2ddeb23396..945502d44d 100644 --- a/server/storage/files/LocalStorage.ts +++ b/server/storage/files/LocalStorage.ts @@ -7,6 +7,7 @@ import fs from "fs-extra"; import invariant from "invariant"; import JWT from "jsonwebtoken"; import safeResolvePath from "resolve-path"; +import { toError } from "@shared/utils/error"; import env from "@server/env"; import { InternalError, ValidationError } from "@server/errors"; import Logger from "@server/logging/Logger"; @@ -95,7 +96,7 @@ export default class LocalStorage extends BaseStorage { try { await unlink(filePath); } catch (err) { - Logger.warn(`Couldn't delete ${filePath}`, err); + Logger.warn(`Couldn't delete ${filePath}`, { error: err }); return; } @@ -103,10 +104,10 @@ export default class LocalStorage extends BaseStorage { try { await rmdir(directory); } catch (err) { - if (err.code === "ENOTEMPTY") { + if (err instanceof Error && "code" in err && err.code === "ENOTEMPTY") { return; } - Logger.warn(`Couldn't delete directory ${directory}`, err); + Logger.warn(`Couldn't delete directory ${directory}`, { error: err }); } } @@ -160,7 +161,7 @@ export default class LocalStorage extends BaseStorage { try { return fs.createReadStream(filePath, range); } catch (err) { - Logger.error(`Failed to create read stream`, err, { filePath }); + Logger.error(`Failed to create read stream`, toError(err), { filePath }); throw ValidationError("Unable to read file"); } } diff --git a/server/storage/files/S3Storage.ts b/server/storage/files/S3Storage.ts index e9d4777971..67606777a9 100644 --- a/server/storage/files/S3Storage.ts +++ b/server/storage/files/S3Storage.ts @@ -17,6 +17,7 @@ import fs from "fs-extra"; import invariant from "invariant"; import { compact } from "es-toolkit/compat"; import tmp from "tmp"; +import { toError } from "@shared/utils/error"; import env from "@server/env"; import Logger from "@server/logging/Logger"; import BaseStorage from "./BaseStorage"; @@ -171,10 +172,14 @@ export default class S3Storage extends BaseStorage { dateLessThan: new Date(Date.now() + expiresIn * 1000).toISOString(), }); } catch (err) { - Logger.error("Failed to sign CloudFront URL, falling back to S3", err, { - key, - cfUrl, - }); + Logger.error( + "Failed to sign CloudFront URL, falling back to S3", + toError(err), + { + key, + cfUrl, + } + ); return this.getS3PresignedUrl(key, expiresIn); } } @@ -302,10 +307,7 @@ export default class S3Storage extends BaseStorage { } // Ensure expiration does not exceed AWS S3 Signature V4 limit of 7 days - const clampedExpiresIn = Math.min( - expiresIn, - S3Storage.maxSignedUrlExpires - ); + const clampedExpiresIn = Math.min(expiresIn, S3Storage.maxSignedUrlExpires); const command = new GetObjectCommand(params); const url = await getSignedUrl(this.client, command, { diff --git a/server/storage/redis.ts b/server/storage/redis.ts index 6625247772..24c08d166f 100644 --- a/server/storage/redis.ts +++ b/server/storage/redis.ts @@ -1,6 +1,7 @@ import type { RedisOptions } from "ioredis"; import Redis from "ioredis"; import { defaults } from "es-toolkit/compat"; +import { errToString } from "@shared/utils/error"; import env from "@server/env"; import Logger from "@server/logging/Logger"; import { getConnectionName } from "./utils"; @@ -56,7 +57,7 @@ export default class RedisAdapter extends Redis { const decodedString = Buffer.from(url.slice(10), "base64").toString(); customOptions = JSON.parse(decodedString); } catch (error) { - const message = error instanceof Error ? error.message : String(error); + const message = errToString(error); throw new Error(`Failed to decode redis adapter options: ${message}`); } @@ -65,7 +66,7 @@ export default class RedisAdapter extends Redis { defaults(options, { connectionName }, customOptions, defaultOptions) ); } catch (error) { - const message = error instanceof Error ? error.message : String(error); + const message = errToString(error); throw new Error(`Failed to initialize redis client: ${message}`); } } diff --git a/server/tools/util.ts b/server/tools/util.ts index f061a158ca..84df635649 100644 --- a/server/tools/util.ts +++ b/server/tools/util.ts @@ -1,6 +1,7 @@ import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js"; import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; import { z } from "zod"; +import { errToString } from "@shared/utils/error"; import { Collection, type Team, type User } from "@server/models"; import { addTags } from "@server/logging/tracer"; import { traceFunction } from "@server/logging/tracing"; @@ -88,7 +89,7 @@ export function success(data: T | T[]): CallToolResult { * @returns a formatted error response object for MCP tools. */ export function error(err: unknown): CallToolResult { - const message = err instanceof Error ? err.message : String(err); + const message = errToString(err); return { content: [{ type: "text" as const, text: message }], diff --git a/server/utils/CacheHelper.ts b/server/utils/CacheHelper.ts index f8d4caa9f7..40107f772f 100644 --- a/server/utils/CacheHelper.ts +++ b/server/utils/CacheHelper.ts @@ -1,3 +1,4 @@ +import { toError } from "@shared/utils/error"; import { Day } from "@shared/utils/time"; import Logger from "@server/logging/Logger"; import Redis from "@server/storage/redis"; @@ -54,7 +55,7 @@ export class CacheHelper { try { lock = await MutexLock.acquire(lockKey, lockTimeout); } catch (err) { - Logger.error(`Could not acquire lock for ${key}`, err); + Logger.error(`Could not acquire lock for ${key}`, toError(err)); } cache = await this.getData(key); if (cache) { @@ -100,7 +101,10 @@ export class CacheHelper { } } catch (err) { // just log it, response can still be obtained using the fetch call - Logger.error(`Could not fetch cached response against ${key}`, err); + Logger.error( + `Could not fetch cached response against ${key}`, + toError(err) + ); } return; } @@ -122,7 +126,7 @@ export class CacheHelper { ); } catch (err) { // just log it, can skip caching and directly return response - Logger.error(`Could not cache response against ${key}`, err); + Logger.error(`Could not cache response against ${key}`, toError(err)); } } @@ -135,7 +139,10 @@ export class CacheHelper { try { await Redis.defaultClient.del(key); } catch (err) { - Logger.error(`Could not remove cached entry against ${key}`, err); + Logger.error( + `Could not remove cached entry against ${key}`, + toError(err) + ); } } diff --git a/server/utils/RateLimiter.ts b/server/utils/RateLimiter.ts index 7f6cfb1347..9c815c9c1c 100644 --- a/server/utils/RateLimiter.ts +++ b/server/utils/RateLimiter.ts @@ -1,6 +1,7 @@ import { createHash } from "crypto"; import type { IRateLimiterStoreOptions } from "rate-limiter-flexible"; import { RateLimiterRedis, RateLimiterMemory } from "rate-limiter-flexible"; +import { toError } from "@shared/utils/error"; import env from "@server/env"; import Logger from "@server/logging/Logger"; import Redis from "@server/storage/redis"; @@ -69,7 +70,7 @@ export default class RateLimiter { this.TOKEN_CACHE_TTL_SECONDS ); } catch (err) { - Logger.warn("Failed to cache user for rate limiter token", err); + Logger.warn("Failed to cache user for rate limiter token", toError(err)); } } @@ -84,7 +85,10 @@ export default class RateLimiter { try { return await Redis.defaultClient.get(this.tokenCacheKey(token)); } catch (err) { - Logger.warn("Failed to read cached user for rate limiter token", err); + Logger.warn( + "Failed to read cached user for rate limiter token", + toError(err) + ); return null; } } @@ -99,7 +103,7 @@ export default class RateLimiter { try { await Redis.defaultClient.del(this.tokenCacheKey(token)); } catch (err) { - Logger.warn("Failed to clear cached rate limiter token", err); + Logger.warn("Failed to clear cached rate limiter token", toError(err)); } } diff --git a/server/utils/authentication.ts b/server/utils/authentication.ts index 4c86f007d3..841182e93a 100644 --- a/server/utils/authentication.ts +++ b/server/utils/authentication.ts @@ -2,6 +2,7 @@ import querystring from "node:querystring"; import { addMonths } from "date-fns"; import type { Context } from "koa"; import { pick } from "es-toolkit/compat"; +import { toError } from "@shared/utils/error"; import { Client } from "@shared/types"; import { getCookieDomain } from "@shared/utils/domains"; import env from "@server/env"; @@ -62,7 +63,7 @@ export async function signIn( } ); } catch (error) { - Logger.error(`Error persisting signup query params`, error); + Logger.error(`Error persisting signup query params`, toError(error)); } } } diff --git a/server/utils/fetch.ts b/server/utils/fetch.ts index 6c59e6a555..cd3b977d23 100644 --- a/server/utils/fetch.ts +++ b/server/utils/fetch.ts @@ -10,6 +10,7 @@ import nodeFetch, { } from "node-fetch"; import { getProxyForUrl } from "proxy-from-env"; import tunnelAgent, { type TunnelAgent } from "tunnel-agent"; +import { errToString } from "@shared/utils/error"; import env from "@server/env"; import { InvalidRequestError } from "@server/errors"; import Logger from "@server/logging/Logger"; @@ -181,14 +182,15 @@ export default async function fetch( return response; } catch (err) { - if (err.name === "AbortError") { + if (err instanceof Error && "name" in err && err.name === "AbortError") { throw new Error(`Request timeout after ${timeout}ms`); } - if (err.message?.startsWith("DNS lookup")) { + const message = errToString(err); + if (message.startsWith("DNS lookup")) { throw InvalidRequestError( env.isCloudHosted - ? err.message - : `${err.message}\n\nTo allow this request, add the IP address or CIDR range to the ALLOWED_PRIVATE_IP_ADDRESSES environment variable.` + ? message + : `${message}\n\nTo allow this request, add the IP address or CIDR range to the ALLOWED_PRIVATE_IP_ADDRESSES environment variable.` ); } throw err; diff --git a/server/utils/getInstallationInfo.ts b/server/utils/getInstallationInfo.ts index be0904756d..59cbabfc4a 100644 --- a/server/utils/getInstallationInfo.ts +++ b/server/utils/getInstallationInfo.ts @@ -1,3 +1,4 @@ +import { errToString } from "@shared/utils/error"; import { version } from "../../package.json"; import Logger from "@server/logging/Logger"; import fetch from "./fetch"; @@ -65,7 +66,7 @@ export async function getVersionInfo(currentVersion: string): Promise<{ "Failed to fetch version information from Docker Hub. This is expected in isolated environments.", { currentVersion, - error: error instanceof Error ? error.message : String(error), + error: errToString(error), } ); diff --git a/server/utils/oauth.test.ts b/server/utils/oauth.test.ts index eb47b9174f..77e1f9eff7 100644 --- a/server/utils/oauth.test.ts +++ b/server/utils/oauth.test.ts @@ -25,7 +25,9 @@ describe("userInfo", () => { expect.assertions(1); await client.userInfo("token"); } catch (e) { - expect(e.id).toBe("authentication_required"); + expect(e instanceof Error && "id" in e ? e.id : undefined).toBe( + "authentication_required" + ); } }); }); diff --git a/server/utils/oauth.ts b/server/utils/oauth.ts index b4732a4d91..ac330b1ffa 100644 --- a/server/utils/oauth.ts +++ b/server/utils/oauth.ts @@ -1,5 +1,6 @@ import { addMinutes, subMinutes } from "date-fns"; import type { Context } from "koa"; +import { errToString } from "@shared/utils/error"; import { randomString } from "@shared/random"; import { getCookieDomain } from "@shared/utils/domains"; import env from "@server/env"; @@ -95,7 +96,7 @@ export default abstract class OAuthClient { }, }); } catch (err) { - throw InvalidRequestError(err.message); + throw InvalidRequestError(errToString(err)); } const success = response.status >= 200 && response.status < 300; @@ -106,7 +107,7 @@ export default abstract class OAuthClient { try { data = await response.json(); } catch (err) { - throw InvalidRequestError(err.message); + throw InvalidRequestError(errToString(err)); } return data; @@ -142,7 +143,7 @@ export default abstract class OAuthClient { }); data = await response.json(); } catch (err) { - throw InvalidRequestError(err.message); + throw InvalidRequestError(errToString(err)); } const success = response.status >= 200 && response.status < 300; diff --git a/server/utils/passport.ts b/server/utils/passport.ts index 117a1d684b..fe766f92dc 100644 --- a/server/utils/passport.ts +++ b/server/utils/passport.ts @@ -6,6 +6,7 @@ import type { StateStoreVerifyCallback, } from "passport-oauth2"; import type { Primitive } from "utility-types"; +import { toError } from "@shared/utils/error"; import { Client } from "@shared/types"; import { getCookieDomain, parseDomain } from "@shared/utils/domains"; import env from "@server/env"; @@ -173,7 +174,7 @@ export class StateStore { try { state = verifyOAuthState(providedToken); } catch (err) { - return callback(err, false, providedToken); + return callback(toError(err), false, providedToken); } if (!safeEqual(hashOAuthStateNonce(csrfNonce ?? ""), state.nonceHash)) { diff --git a/server/utils/startup.ts b/server/utils/startup.ts index 0a40f22cbe..b5cd53896c 100644 --- a/server/utils/startup.ts +++ b/server/utils/startup.ts @@ -1,5 +1,6 @@ import { styleText } from "node:util"; import { isEmpty } from "es-toolkit/compat"; +import { toError, errToString } from "@shared/utils/error"; import env from "@server/env"; import Logger from "@server/logging/Logger"; import AuthenticationProvider from "@server/models/AuthenticationProvider"; @@ -33,16 +34,18 @@ export async function checkPendingMigrations() { } await checkDataMigrations(); } catch (err) { - if (err.message.includes("ECONNREFUSED")) { + const message = errToString(err); + const error = toError(err); + if (message.includes("ECONNREFUSED")) { Logger.fatal( styleText( "red", `Could not connect to the database. Please check your connection settings.` ), - err + error ); } else { - Logger.fatal(styleText("red", err.message), err); + Logger.fatal(styleText("red", message), error); } } finally { if (lock) { diff --git a/shared/editor/extensions/Mermaid.ts b/shared/editor/extensions/Mermaid.ts index 2ac9e8de0a..d49425debc 100644 --- a/shared/editor/extensions/Mermaid.ts +++ b/shared/editor/extensions/Mermaid.ts @@ -8,6 +8,7 @@ import type { Transaction } from "prosemirror-state"; import { NodeSelection, Plugin, PluginKey } from "prosemirror-state"; import { Decoration, DecorationSet } from "prosemirror-view"; import { toast } from "sonner"; +import { errToString } from "../../utils/error"; import { isCode, isMermaid } from "../lib/isCode"; import { isRemoteTransaction, mapDecorations } from "../lib/multiplayer"; import { findBlockNodes } from "../queries/findChildren"; @@ -262,7 +263,7 @@ class MermaidRenderer { element.innerText = "Empty diagram"; element.classList.add("empty"); } else { - element.innerText = error; + element.innerText = errToString(error); element.classList.add("parse-error"); } } finally { diff --git a/shared/editor/lib/uploadPlaceholder.tsx b/shared/editor/lib/uploadPlaceholder.tsx index 8c602de984..b8f7738924 100644 --- a/shared/editor/lib/uploadPlaceholder.tsx +++ b/shared/editor/lib/uploadPlaceholder.tsx @@ -11,7 +11,7 @@ const uploadPlaceholder = new Plugin({ init() { return DecorationSet.empty; }, - apply(tr, set: DecorationSet) { + apply(this: Plugin, tr, set: DecorationSet) { // See if the transaction adds or removes any placeholders – the placeholder display is // different depending on if we're uploading an image, video or plain file const action = tr.getMeta(this); diff --git a/shared/utils/error.test.ts b/shared/utils/error.test.ts new file mode 100644 index 0000000000..05d78835e2 --- /dev/null +++ b/shared/utils/error.test.ts @@ -0,0 +1,36 @@ +import { toError, errToString } from "./error"; + +describe("toError", () => { + it("returns the same Error instance when given an Error", () => { + const error = new Error("boom"); + expect(toError(error)).toBe(error); + }); + + it("preserves Error subclasses", () => { + const error = new TypeError("nope"); + expect(toError(error)).toBe(error); + }); + + it("wraps a string in an Error", () => { + expect(toError("boom")).toBeInstanceOf(Error); + expect(toError("boom").message).toBe("boom"); + }); + + it("wraps non-string values using their string representation", () => { + expect(toError(42).message).toBe("42"); + expect(toError(null).message).toBe("null"); + expect(toError(undefined).message).toBe("undefined"); + }); +}); + +describe("errToString", () => { + it("returns the message of an Error", () => { + expect(errToString(new Error("boom"))).toBe("boom"); + }); + + it("returns the string representation of a non-Error", () => { + expect(errToString("boom")).toBe("boom"); + expect(errToString(42)).toBe("42"); + expect(errToString(undefined)).toBe("undefined"); + }); +}); diff --git a/shared/utils/error.ts b/shared/utils/error.ts new file mode 100644 index 0000000000..ba5a45cf26 --- /dev/null +++ b/shared/utils/error.ts @@ -0,0 +1,19 @@ +/** + * Coerce an unknown value, such as a value caught in a try/catch, to an Error. + * + * @param value the value to coerce, typically a caught error. + * @returns the value itself when it is already an Error, otherwise a new Error wrapping its string representation. + */ +export function toError(value: unknown): Error { + return value instanceof Error ? value : new Error(String(value)); +} + +/** + * Extract a human-readable message from an unknown value, such as a value caught in a try/catch. + * + * @param value the value to read a message from, typically a caught error. + * @returns the Error's message when it is an Error, otherwise its string representation. + */ +export function errToString(value: unknown): string { + return value instanceof Error ? value.message : String(value); +} diff --git a/shared/utils/files.ts b/shared/utils/files.ts index ea3ba88f4a..da13b04287 100644 --- a/shared/utils/files.ts +++ b/shared/utils/files.ts @@ -104,7 +104,7 @@ export function getDataTransferFiles( .call(dt.items) .filter((dti: DataTransferItem) => dti.kind !== "string") .map((dti: DataTransferItem) => dti.getAsFile()) - .filter(Boolean) + .filter((file: File | null): file is File => file !== null) : []; } } diff --git a/tsconfig.json b/tsconfig.json index 0384b882dd..67b46190f8 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,5 +1,6 @@ { "compilerOptions": { + "strict": false, "allowSyntheticDefaultImports": true, "alwaysStrict": true, "esModuleInterop": true, @@ -16,11 +17,13 @@ "noImplicitAny": true, "noImplicitOverride": false, "noImplicitReturns": true, - "noImplicitThis": false, + "noImplicitThis": true, + "useUnknownInCatchVariables": true, "sourceMap": true, "resolveJsonModule": true, "strictNullChecks": true, "noEmit": true, + "strictBindCallApply": true, "skipLibCheck": true, "ignoreDeprecations": "5.0", "target": "es2020", diff --git a/yarn.lock b/yarn.lock index 26fd94e34a..e24d473001 100644 --- a/yarn.lock +++ b/yarn.lock @@ -15260,7 +15260,7 @@ __metadata: tiny-cookie: "npm:^2.5.1" tmp: "npm:^0.2.6" tunnel-agent: "npm:^0.6.0" - typescript: "npm:^5.9.3" + typescript: "npm:^6.0.3" ukkonen: "npm:^2.2.0" umzug: "npm:^3.8.3" unplugin-swc: "npm:^1.5.9" @@ -19298,7 +19298,7 @@ __metadata: languageName: node linkType: hard -"typescript@npm:^5.0.4, typescript@npm:^5.9.3": +"typescript@npm:^5.0.4": version: 5.9.3 resolution: "typescript@npm:5.9.3" bin: @@ -19308,7 +19308,17 @@ __metadata: languageName: node linkType: hard -"typescript@patch:typescript@npm%3A^5.0.4#optional!builtin, typescript@patch:typescript@npm%3A^5.9.3#optional!builtin": +"typescript@npm:^6.0.3": + version: 6.0.3 + resolution: "typescript@npm:6.0.3" + bin: + tsc: bin/tsc + tsserver: bin/tsserver + checksum: 10c0/4a25ff5045b984370f48f196b3a0120779b1b343d40b9a68d114ea5e5fff099809b2bb777576991a63a5cd59cf7bffd96ff6fe10afcefbcb8bd6fb96ad4b6606 + languageName: node + linkType: hard + +"typescript@patch:typescript@npm%3A^5.0.4#optional!builtin": version: 5.9.3 resolution: "typescript@patch:typescript@npm%3A5.9.3#optional!builtin::version=5.9.3&hash=5786d5" bin: @@ -19318,6 +19328,16 @@ __metadata: languageName: node linkType: hard +"typescript@patch:typescript@npm%3A^6.0.3#optional!builtin": + version: 6.0.3 + resolution: "typescript@patch:typescript@npm%3A6.0.3#optional!builtin::version=6.0.3&hash=5786d5" + bin: + tsc: bin/tsc + tsserver: bin/tsserver + checksum: 10c0/2f25c74e65663c248fa1ade2b8459d9ce5372ff9dad07067310f132966ebec1d93f6c42f0baf77a6b6a7a91460463f708e6887013aaade22111037457c6b25df + languageName: node + linkType: hard + "uc.micro@npm:^2.0.0, uc.micro@npm:^2.1.0": version: 2.1.0 resolution: "uc.micro@npm:2.1.0"