A local-first personal finance app
Improve category server app and react query mutation error handling (#6958)
Joel Jeremy Marquez180a38890ccf
diff --git a/packages/desktop-client/src/budget/mutations.ts b/packages/desktop-client/src/budget/mutations.tsindex 01138d460b..5d499df51d 100644--- a/packages/desktop-client/src/budget/mutations.ts+++ b/packages/desktop-client/src/budget/mutations.ts@@ -5,8 +5,7 @@ import type { QueryClient, QueryKey } from '@tanstack/react-query';import type { TFunction } from 'i18next';import { v4 as uuidv4 } from 'uuid';-import { sendCatch } from 'loot-core/platform/client/connection';-import type { send } from 'loot-core/platform/client/connection';+import { send } from 'loot-core/platform/client/connection';import type { IntegerAmount } from 'loot-core/shared/util';import type {CategoryEntity,@@ -20,14 +19,6 @@ import { addNotification } from '@desktop-client/notifications/notificationsSlicimport { useDispatch } from '@desktop-client/redux';import type { AppDispatch } from '@desktop-client/redux/store';-const sendThrow: typeof send = async (name, args) => {- const { error, data } = await sendCatch(name, args);- if (error) {- throw error;- }- return data;-};-function invalidateQueries(queryClient: QueryClient, queryKey?: QueryKey) {queryClient.invalidateQueries({queryKey: queryKey ?? categoryQueries.lists(),@@ -88,7 +79,7 @@ export function useCreateCategoryMutation() {isIncome,isHidden,}: CreateCategoryPayload) => {- const id = await sendThrow('category-create', {+ const id = await send('category-create', {name,groupId,isIncome,@@ -104,7 +95,6 @@ export function useCreateCategoryMutation() {t('There was an error creating the category. Please try again.'),error,);- throw error;},});}@@ -120,7 +110,7 @@ export function useUpdateCategoryMutation() {return useMutation({mutationFn: async ({ category }: UpdateCategoryPayload) => {- await sendThrow('category-update', category);+ await send('category-update', category);},onSuccess: () => invalidateQueries(queryClient),onError: error => {@@ -130,7 +120,6 @@ export function useUpdateCategoryMutation() {t('There was an error updating the category. Please try again.'),error,);- throw error;},});}@@ -198,12 +187,12 @@ export function useDeleteCategoryMutation() {id: CategoryEntity['id'];transferId?: CategoryEntity['id'];}) => {- await sendThrow('category-delete', { id, transferId });+ await send('category-delete', { id, transferId });};return useMutation({mutationFn: async ({ id }: DeleteCategoryPayload) => {- const mustTransfer = await sendThrow('must-category-transfer', { id });+ const mustTransfer = await send('must-category-transfer', { id });if (mustTransfer) {dispatch(@@ -228,28 +217,11 @@ export function useDeleteCategoryMutation() {onSuccess: () => invalidateQueries(queryClient),onError: error => {console.error('Error deleting category:', error);-- if (error) {- switch (error.cause) {- case 'category-type':- dispatchErrorNotification(- dispatch,- t(- 'A category must be transferred to another of the same type (expense or income)',- ),- error,- );- break;- default:- dispatchErrorNotification(- dispatch,- t('There was an error deleting the category. Please try again.'),- error,- );- }- }-- throw error;+ dispatchErrorNotification(+ dispatch,+ t('There was an error deleting the category. Please try again.'),+ error,+ );},});}@@ -267,7 +239,7 @@ export function useMoveCategoryMutation() {return useMutation({mutationFn: async ({ id, groupId, targetId }: MoveCategoryPayload) => {- await sendThrow('category-move', { id, groupId, targetId });+ await send('category-move', { id, groupId, targetId });},onSuccess: () => invalidateQueries(queryClient),onError: error => {@@ -277,7 +249,6 @@ export function useMoveCategoryMutation() {t('There was an error moving the category. Please try again.'),error,);- throw error;},});}@@ -333,7 +304,7 @@ export function useCreateCategoryGroupMutation() {return useMutation({mutationFn: async ({ name }: CreateCategoryGroupPayload) => {- const id = await sendThrow('category-group-create', { name });+ const id = await send('category-group-create', { name });return id;},onSuccess: () => invalidateQueries(queryClient),@@ -344,7 +315,6 @@ export function useCreateCategoryGroupMutation() {t('There was an error creating the category group. Please try again.'),error,);- throw error;},});}@@ -382,7 +352,7 @@ export function useUpdateCategoryGroupMutation() {// Strip off the categories field if it exist. It's not a real db// field but groups have this extra field in the client most of the timeconst { categories: _, ...groupNoCategories } = group;- await sendThrow('category-group-update', groupNoCategories);+ await send('category-group-update', groupNoCategories);},onSuccess: () => invalidateQueries(queryClient),onError: error => {@@ -392,7 +362,6 @@ export function useUpdateCategoryGroupMutation() {t('There was an error updating the category group. Please try again.'),error,);- throw error;},});}@@ -440,7 +409,7 @@ export function useDeleteCategoryGroupMutation() {let mustTransfer = false;for (const category of categories) {- if (await sendThrow('must-category-transfer', { id: category.id })) {+ if (await send('must-category-transfer', { id: category.id })) {mustTransfer = true;break;}@@ -454,7 +423,7 @@ export function useDeleteCategoryGroupMutation() {options: {group: id,onDelete: async transferCategory => {- await sendThrow('category-group-delete', {+ await send('category-group-delete', {id,transferId: transferCategory,});@@ -464,7 +433,7 @@ export function useDeleteCategoryGroupMutation() {}),);} else {- await sendThrow('category-group-delete', { id });+ await send('category-group-delete', { id });}},onSuccess: () => invalidateQueries(queryClient),@@ -475,7 +444,6 @@ export function useDeleteCategoryGroupMutation() {t('There was an error deleting the category group. Please try again.'),error,);- throw error;},});}@@ -492,7 +460,7 @@ export function useMoveCategoryGroupMutation() {return useMutation({mutationFn: async ({ id, targetId }: MoveCategoryGroupPayload) => {- await sendThrow('category-group-move', { id, targetId });+ await send('category-group-move', { id, targetId });},onSuccess: () => invalidateQueries(queryClient),onError: error => {@@ -502,7 +470,6 @@ export function useMoveCategoryGroupMutation() {t('There was an error moving the category group. Please try again.'),error,);- throw error;},});}@@ -692,51 +659,51 @@ export function useBudgetActions() {mutationFn: async ({ month, type, args }: ApplyBudgetActionPayload) => {switch (type) {case 'budget-amount':- await sendThrow('budget/budget-amount', {+ await send('budget/budget-amount', {month,category: args.category,amount: args.amount,});return null;case 'copy-last':- await sendThrow('budget/copy-previous-month', { month });+ await send('budget/copy-previous-month', { month });return null;case 'set-zero':- await sendThrow('budget/set-zero', { month });+ await send('budget/set-zero', { month });return null;case 'set-3-avg':- await sendThrow('budget/set-3month-avg', { month });+ await send('budget/set-3month-avg', { month });return null;case 'set-6-avg':- await sendThrow('budget/set-6month-avg', { month });+ await send('budget/set-6month-avg', { month });return null;case 'set-12-avg':- await sendThrow('budget/set-12month-avg', { month });+ await send('budget/set-12month-avg', { month });return null;case 'check-templates':- return await sendThrow('budget/check-templates');+ return await send('budget/check-templates');case 'apply-goal-template':- return await sendThrow('budget/apply-goal-template', { month });+ return await send('budget/apply-goal-template', { month });case 'overwrite-goal-template':- return await sendThrow('budget/overwrite-goal-template', { month });+ return await send('budget/overwrite-goal-template', { month });case 'apply-single-category-template':- return await sendThrow('budget/apply-single-template', {+ return await send('budget/apply-single-template', {month,category: args.category,});case 'cleanup-goal-template':- return await sendThrow('budget/cleanup-goal-template', { month });+ return await send('budget/cleanup-goal-template', { month });case 'hold':- await sendThrow('budget/hold-for-next-month', {+ await send('budget/hold-for-next-month', {month,amount: args.amount,});return null;case 'reset-hold':- await sendThrow('budget/reset-hold', { month });+ await send('budget/reset-hold', { month });return null;case 'cover-overspending':- await sendThrow('budget/cover-overspending', {+ await send('budget/cover-overspending', {month,to: args.to,from: args.from,@@ -745,14 +712,14 @@ export function useBudgetActions() {});return null;case 'transfer-available':- await sendThrow('budget/transfer-available', {+ await send('budget/transfer-available', {month,amount: args.amount,category: args.category,});return null;case 'cover-overbudgeted':- await sendThrow('budget/cover-overbudgeted', {+ await send('budget/cover-overbudgeted', {month,category: args.category,amount: args.amount,@@ -760,7 +727,7 @@ export function useBudgetActions() {});return null;case 'transfer-category':- await sendThrow('budget/transfer-category', {+ await send('budget/transfer-category', {month,amount: args.amount,from: args.from,@@ -769,7 +736,7 @@ export function useBudgetActions() {});return null;case 'carryover': {- await sendThrow('budget/set-carryover', {+ await send('budget/set-carryover', {startMonth: month,category: args.category,flag: args.flag,@@ -777,36 +744,36 @@ export function useBudgetActions() {return null;}case 'reset-income-carryover':- await sendThrow('budget/reset-income-carryover', { month });+ await send('budget/reset-income-carryover', { month });return null;case 'apply-multiple-templates':- return await sendThrow('budget/apply-multiple-templates', {+ return await send('budget/apply-multiple-templates', {month,categoryIds: args.categories,});case 'set-single-3-avg':- await sendThrow('budget/set-n-month-avg', {+ await send('budget/set-n-month-avg', {month,N: 3,category: args.category,});return null;case 'set-single-6-avg':- await sendThrow('budget/set-n-month-avg', {+ await send('budget/set-n-month-avg', {month,N: 6,category: args.category,});return null;case 'set-single-12-avg':- await sendThrow('budget/set-n-month-avg', {+ await send('budget/set-n-month-avg', {month,N: 12,category: args.category,});return null;case 'copy-single-last':- await sendThrow('budget/copy-single-month', {+ await send('budget/copy-single-month', {month,category: args.category,});@@ -831,7 +798,6 @@ export function useBudgetActions() {t('There was an error applying the budget action. Please try again.'),error,);- throw error;},});}diff --git a/packages/loot-core/src/platform/client/connection/index-types.ts b/packages/loot-core/src/platform/client/connection/index-types.tsindex ef2b62e98a..5601523e7e 100644--- a/packages/loot-core/src/platform/client/connection/index-types.ts+++ b/packages/loot-core/src/platform/client/connection/index-types.ts@@ -24,7 +24,7 @@ export declare function send<K extends keyof Handlers>(| {data: undefined;error: {- type: 'APIError' | 'InternalError';+ type: 'APIError' | 'ServerError';message: string;cause?: unknown;};@@ -53,7 +53,7 @@ export declare function sendCatch<K extends keyof Handlers>(| {data: undefined;error: {- type: 'APIError' | 'InternalError';+ type: 'APIError' | 'ServerError';message: string;cause?: unknown;};diff --git a/packages/loot-core/src/platform/server/connection/index.electron.ts b/packages/loot-core/src/platform/server/connection/index.electron.tsindex b13701019d..8d9b4f9c62 100644--- a/packages/loot-core/src/platform/server/connection/index.electron.ts+++ b/packages/loot-core/src/platform/server/connection/index.electron.ts@@ -11,7 +11,7 @@ function coerceError(error) {return error;}- return { type: 'InternalError', message: error.message, cause: error };+ return { type: 'ServerError', message: error.message, cause: error };}export const init: T.Init = function (_socketName, handlers) {@@ -55,7 +55,7 @@ export const init: T.Init = function (_socketName, handlers) {process.parentPort.postMessage({ type: 'error', id, error });}- if (error.type === 'InternalError' && name !== 'api/load-budget') {+ if (error.type === 'ServerError' && name !== 'api/load-budget') {captureException(nativeError);}diff --git a/packages/loot-core/src/platform/server/connection/index.ts b/packages/loot-core/src/platform/server/connection/index.tsindex ef0c4b91f6..8bedbfadee 100644--- a/packages/loot-core/src/platform/server/connection/index.ts+++ b/packages/loot-core/src/platform/server/connection/index.ts@@ -28,7 +28,7 @@ function coerceError(error) {return error;}- return { type: 'InternalError', message: error.message, cause: error };+ return { type: 'ServerError', message: error.message, cause: error };}export const init: T.Init = function (serverChn, handlers) {@@ -83,7 +83,7 @@ export const init: T.Init = function (serverChn, handlers) {}// Only report internal errors- if (error.type === 'InternalError') {+ if (error.type === 'ServerError') {captureException(nativeError);}diff --git a/packages/loot-core/src/server/budget/app.ts b/packages/loot-core/src/server/budget/app.tsindex d37753a985..ed6e4a5b37 100644--- a/packages/loot-core/src/server/budget/app.ts+++ b/packages/loot-core/src/server/budget/app.ts@@ -295,9 +295,7 @@ async function createCategory({});}-async function updateCategory(- category: CategoryEntity,-): Promise<{ error: { type: 'category-exists' } } | object> {+async function updateCategory(category: CategoryEntity): Promise<void> {try {await db.updateCategory(categoryModel.toDb({@@ -310,11 +308,13 @@ async function updateCategory(e instanceof Error &&e.message.toLowerCase().includes('unique constraint')) {- return { error: { type: 'category-exists' } };+ throw new Error(+ `A category with the name "${category.name}" already exists.`,+ { cause: e },+ );}throw e;}- return {};}async function moveCategory({@@ -337,16 +337,14 @@ async function deleteCategory({}: {id: CategoryEntity['id'];transferId?: CategoryEntity['id'] | null;-}): Promise<{ error?: 'no-categories' | 'category-type' }> {- let result = {};+}): Promise<void> {await batchMessages(async () => {const row = await db.first<Pick<db.DbCategory, 'is_income'>>('SELECT is_income FROM categories WHERE id = ?',[id],);if (!row) {- result = { error: 'no-categories' };- return;+ throw new Error(`Category with id ${id} not found.`);}const transfer =@@ -356,17 +354,15 @@ async function deleteCategory({[transferId],));- if (!row || (transferId && !transfer)) {- result = { error: 'no-categories' };- return;+ if (transferId && !transfer) {+ throw new Error(`Transfer category with id ${transferId} not found.`);} else if (transferId &&row &&transfer &&row.is_income !== transfer.is_income) {- result = { error: 'category-type' };- return;+ throw new Error('Cannot transfer between income and expense categories.');}// Update spreadsheet values if it's an expense category@@ -379,8 +375,6 @@ async function deleteCategory({await db.deleteCategory({ id }, transferId);});-- return result;}// Server must return AQL entities not the raw DB datadiff --git a/packages/loot-core/src/server/main.test.ts b/packages/loot-core/src/server/main.test.tsindex 9a06e47000..8d648e4e4a 100644--- a/packages/loot-core/src/server/main.test.ts+++ b/packages/loot-core/src/server/main.test.ts@@ -372,11 +372,12 @@ describe('Categories', () => {// Transfering an income category to an expense just doesn't make// sense. Make sure this doesn't do anything.- const { error } = await runHandler(handlers['category-delete'], {- id: 'income1',- transferId: 'bar',- });- expect(error).toBe('category-type');+ await expect(+ runHandler(handlers['category-delete'], {+ id: 'income1',+ transferId: 'bar',+ }),+ ).rejects.toThrow('Cannot transfer between income and expense categories.');let categories = await db.getCategories();expect(categories.find(cat => cat.id === 'income1')).toBeDefined();diff --git a/packages/loot-core/src/server/sync/index.ts b/packages/loot-core/src/server/sync/index.tsindex 1143c4ea6b..245de001be 100644--- a/packages/loot-core/src/server/sync/index.ts+++ b/packages/loot-core/src/server/sync/index.ts@@ -487,7 +487,7 @@ export async function batchMessages(func: () => Promise<void>): Promise<void> {await func();} catch (e) {errorHandler(e);- // TODO: if it fails, it shouldn't apply them?+ throw e;} finally {IS_BATCHING = false;batched = _BATCHED;diff --git a/packages/loot-core/src/types/api-handlers.ts b/packages/loot-core/src/types/api-handlers.tsindex 5f9b4a9f93..665bd76175 100644--- a/packages/loot-core/src/types/api-handlers.ts+++ b/packages/loot-core/src/types/api-handlers.ts@@ -187,14 +187,12 @@ export type ApiHandlers = {fields;// TODO: fix me// fields: Partial<APICategoryEntity>;- }) => Promise<{ error: { type: 'category-exists' } } | object>;+ }) => Promise<void>;'api/category-delete': (arg: {id: APICategoryEntity['id'];transferCategoryId?: APICategoryEntity['id'];- }) => Promise<- { error: 'no-categories' } | { error: 'category-type' } | object- >;+ }) => Promise<void>;'api/payees-get': () => Promise<APIPayeeEntity[]>;diff --git a/upcoming-release-notes/6958.md b/upcoming-release-notes/6958.mdnew file mode 100644index 0000000000..2f78af880c--- /dev/null+++ b/upcoming-release-notes/6958.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [joel-jeremy]+---++Improve error handling in category server app and React Query mutations for better clarity.