Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: error handling try statements #1361

Merged
merged 11 commits into from
Dec 17, 2024
6 changes: 1 addition & 5 deletions NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -950,10 +950,6 @@ The Initial Developer of [email protected],
is David Mark Clements (https://github.com/davidmarkclements/atomic-sleep).
Copyright David Mark Clements. All Rights Reserved.

The Initial Developer of [email protected],
is Matt Zabriskie (https://github.com/axios/axios).
Copyright Matt Zabriskie. All Rights Reserved.

The Initial Developer of [email protected],
is Matt Zabriskie (https://github.com/axios/axios).
Copyright Matt Zabriskie. All Rights Reserved.
Expand Down Expand Up @@ -2188,7 +2184,7 @@ The Initial Developer of [email protected],
is https://github.com/felanios (https://github.com/felanios/murlock).
Copyright https://github.com/felanios. All Rights Reserved.

The Initial Developer of [email protected].7,
The Initial Developer of [email protected].8,
is Andrey Sitnik (https://github.com/ai/nanoid).
Copyright Andrey Sitnik. All Rights Reserved.

Expand Down
11 changes: 4 additions & 7 deletions front-end/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ import createMenu from '@main/modules/menu';
import handleDeepLink, { PROTOCOL_NAME } from '@main/modules/deepLink';
import registerIpcListeners from '@main/modules/ipcHandlers';

import { restoreOrCreateWindow } from '@main/windows/mainWindow';
import { safeAwait } from '@main/utils/safeAwait';
import { deleteAllTempFolders } from '@main/services/localUser';

import { deleteAllTempFolders } from './services/localUser';
import { restoreOrCreateWindow } from '@main/windows/mainWindow';

let mainWindow: BrowserWindow | null;

Expand Down Expand Up @@ -66,11 +67,7 @@ function attachAppEvents() {
e.preventDefault();

deleteRetires++;
try {
await deleteAllTempFolders();
} catch {
/* Empty */
}
await safeAwait(deleteAllTempFolders());

app.quit();
}
Expand Down
7 changes: 1 addition & 6 deletions front-end/src/main/modules/ipcHandlers/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,7 @@ export default () => {
});
if (!filePath.trim() || canceled) return;

try {
await fs.writeFile(filePath, Uint8Array.from(content));
} catch (error: any) {
dialog.showErrorBox('Failed to save file', error?.message || 'Unknown error');
console.log(error);
}
await fs.writeFile(filePath, Uint8Array.from(content));
} catch (error: any) {
dialog.showErrorBox('Failed to save file', error?.message || 'Unknown error');
}
Expand Down
48 changes: 25 additions & 23 deletions front-end/src/main/services/localUser/dataMigration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
} from '@main/shared/constants';

import { parseNetwork } from '@main/utils/parsers';
import { safeAwait } from '@main/utils/safeAwait';

import { addAccount } from './accounts';
import { addClaim } from './claim';
Expand Down Expand Up @@ -237,14 +238,15 @@ export async function migrateUserData(userId: string): Promise<MigrateUserDataRe
parsedContent[USER_PROPERTIES_DEFAULT_MAX_TRANSACTION_FEE_KEY],
);
if (!isNaN(defaultMaxTransactionFee)) {
try {
result.defaultMaxTransactionFee = defaultMaxTransactionFee;
await addClaim(
result.defaultMaxTransactionFee = defaultMaxTransactionFee;
const { error } = await safeAwait(
addClaim(
userId,
DEFAULT_MAX_TRANSACTION_FEE_CLAIM_KEY,
Hbar.fromTinybars(result.defaultMaxTransactionFee).toString(HbarUnit.Tinybar),
);
} catch (error) {
),
);
if (error) {
console.log(error);
}
}
Expand All @@ -253,24 +255,22 @@ export async function migrateUserData(userId: string): Promise<MigrateUserDataRe
parsedContent[USER_PROPERTIES_CURRENT_NETWORK_KEY],
defaultNetwork,
);
try {
result.currentNetwork = defaultNetwork;
await addClaim(userId, SELECTED_NETWORK, defaultNetwork);
} catch (error) {
result.currentNetwork = defaultNetwork;
const { error } = await safeAwait(addClaim(userId, SELECTED_NETWORK, defaultNetwork));
if (error) {
console.log(error);
}

try {
const credentialsObj = parsedContent[CREDENTIALS_DIRECTORY];
if (credentialsObj && typeof credentialsObj === 'object') {
let updatesLocation = Object.keys(credentialsObj)[0];
updatesLocation = updatesLocation.endsWith('/InputFiles')
? updatesLocation
: updatesLocation + '/InputFiles';
await addClaim(userId, UPDATE_LOCATION, updatesLocation);
const credentialsObj = parsedContent[CREDENTIALS_DIRECTORY];
if (credentialsObj && typeof credentialsObj === 'object') {
let updatesLocation = Object.keys(credentialsObj)[0];
updatesLocation = updatesLocation.endsWith('/InputFiles')
? updatesLocation
: updatesLocation + '/InputFiles';
const { error } = await safeAwait(addClaim(userId, UPDATE_LOCATION, updatesLocation));
if (error) {
console.log(error);
}
} catch (error) {
console.log(error);
}
} catch (error) {
console.log(error);
Expand All @@ -280,11 +280,13 @@ export async function migrateUserData(userId: string): Promise<MigrateUserDataRe
const accountDataList = await getAccountInfoFromFile(getAccountsPath(), defaultNetwork);

for (const accountData of accountDataList) {
try {
await addAccount(userId, accountData.accountID, accountData.network, accountData.nickname);
result.accountsImported++;
} catch (error) {
const { error } = await safeAwait(
addAccount(userId, accountData.accountID, accountData.network, accountData.nickname),
);
if (error) {
console.log(error);
} else {
result.accountsImported++;
}
}
} catch (error) {
Expand Down
9 changes: 3 additions & 6 deletions front-end/src/main/services/localUser/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { HederaFile, Prisma } from '@prisma/client';

import { getPrismaClient } from '@main/db/prisma';
import { deleteDirectory, getNumberArrayFromString, saveContentToPath } from '@main/utils';
import { safeAwait } from '@main/utils/safeAwait';

export const getFiles = async (findArgs: Prisma.HederaFileFindManyArgs) => {
const prisma = getPrismaClient();
Expand Down Expand Up @@ -140,12 +141,8 @@ export const showContentInTemp = async (content: Buffer, fileId: string) => {
};

export const deleteTempFolder = async (folder: string) => {
try {
const directoryPath = path.join(app.getPath('temp'), folder);
await deleteDirectory(directoryPath);
} catch {
/* Empty */
}
const directoryPath = path.join(app.getPath('temp'), folder);
await safeAwait(deleteDirectory(directoryPath));
};

export const deleteAllTempFolders = async () => {
Expand Down
4 changes: 2 additions & 2 deletions front-end/src/main/services/localUser/keyPairs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,9 @@ export const storeKeyPair = async (
await prisma.keyPair.create({
data: keyPair,
});
} catch (error: any) {
} catch (error: unknown) {
console.log(error);
throw new Error(error.message || 'Failed to store key pair');
throw new Error(error instanceof Error ? error.message : 'Failed to store key pair');
}
};

Expand Down
4 changes: 2 additions & 2 deletions front-end/src/main/services/localUser/transactionDrafts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ export const getDraftsCount = async (userId: string) => {
});

return count;
} catch (error: any) {
throw new Error(error.message || 'Failed to get drafts count');
} catch (error: unknown) {
throw new Error(error instanceof Error ? error.message : 'Failed to get drafts count');
}
};
8 changes: 4 additions & 4 deletions front-end/src/main/services/localUser/transactionGroups.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ export const getGroups = async (findArgs: Prisma.TransactionGroupFindManyArgs) =

try {
return await prisma.transactionGroup.findMany(findArgs);
} catch (error: any) {
throw new Error(error.message || 'Failed to fetch transaction groups');
} catch (error: unknown) {
throw new Error(error instanceof Error ? error.message : 'Failed to fetch transaction groups');
}
};

Expand Down Expand Up @@ -109,8 +109,8 @@ export const getGroupsCount = async (userId: string) => {
});

return count;
} catch (error: any) {
throw new Error(error.message || 'Failed to get drafts count');
} catch (error: unknown) {
throw new Error(error instanceof Error ? error.message : 'Failed to get drafts count');
}
};

Expand Down
26 changes: 14 additions & 12 deletions front-end/src/main/services/localUser/transactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,10 +193,10 @@ export const executeQuery = async (
} else {
return response;
}
} catch (error: any) {
} catch (error: unknown) {
console.log(error);
client._operator = null;
throw new Error(error.message);
throw new Error(error instanceof Error ? error.message : 'Failed to execute query');
}
};

Expand All @@ -216,9 +216,9 @@ export const storeTransaction = async (transaction: Prisma.TransactionUncheckedC
return await prisma.transaction.create({
data: transaction,
});
} catch (error: any) {
} catch (error: unknown) {
console.log(error);
throw new Error(error.message || 'Failed to store transaction');
throw new Error(error instanceof Error ? error.message : 'Failed to store transaction');
}
};

Expand All @@ -234,8 +234,8 @@ export const getTransactions = async (findArgs: Prisma.TransactionFindManyArgs)
});

return transactions;
} catch (error: any) {
throw new Error(error.message || 'Failed to fetch transactions');
} catch (error: unknown) {
throw new Error(error instanceof Error ? error.message : 'Failed to fetch transactions');
}
};

Expand All @@ -251,8 +251,8 @@ export const getTransactionsCount = async (userId: string) => {
});

return count;
} catch (error: any) {
throw new Error(error.message || 'Failed to get transactions count');
} catch (error: unknown) {
throw new Error(error instanceof Error ? error.message : 'Failed to get transactions count');
}
};

Expand All @@ -272,8 +272,10 @@ export const getTransaction = async (id: string) => {
transaction.body = Uint8Array.from(Buffer.from(transaction.body, 'hex')).toString();

return transaction;
} catch (error: any) {
throw new Error(error.message || `Failed to fetch transaction with id: ${id}`);
} catch (error: unknown) {
throw new Error(
error instanceof Error ? error.message : `Failed to fetch transaction with id: ${id}`,
);
}
};

Expand All @@ -285,8 +287,8 @@ export const encodeSpecialFile = async (content: Uint8Array, fileId: string) =>
} else {
throw new Error('File is not one of special files');
}
} catch (error: any) {
} catch (error: unknown) {
console.log(error);
throw new Error(error.message || 'Failed to encode special file');
throw new Error(error instanceof Error ? error.message : 'Failed to encode special file');
}
};
52 changes: 52 additions & 0 deletions front-end/src/main/utils/safeAwait.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
interface ISafeAwaitResultData<T> {
data: T;
error?: never;
}
interface ISafeAwaitResultError {
data?: never;
error: unknown;
}
export type ISafeAwaitResult<T> = ISafeAwaitResultData<T> | ISafeAwaitResultError;
const nativeExceptions = [
EvalError,
RangeError,
ReferenceError,
SyntaxError,
TypeError,
URIError,
].filter(except => typeof except === 'function');
const throwNative = (error?: Error) => {
for (const Exception of nativeExceptions) {
if (error instanceof Exception) {
throw error;
}
}
};
export const safeAwait = async <T>(promise: Promise<T>): Promise<ISafeAwaitResult<T>> => {
try {
const data = await promise;
if (data instanceof Error) {
throwNative(data);
return { error: data };
}
return { data } as ISafeAwaitResultData<T>;
} catch (error: unknown) {
throwNative(error as Error);
return { error };
}
};
export const safeAwaitAll = async <T extends unknown[]>(
promises: { [K in keyof T]: Promise<T[K]> },
finallyFunc?: () => Promise<void> | void,
): Promise<{ [K in keyof T]: ISafeAwaitResult<T[K]> }> => {
try {
const results = await Promise.all(promises.map(p => safeAwait(p)));
return results as { [K in keyof T]: ISafeAwaitResult<T[K]> };
} catch (error: unknown) {
return promises.map(() => ({ error }) as ISafeAwaitResultError) as {
[K in keyof T]: ISafeAwaitResult<T[K]>;
};
} finally {
await finallyFunc?.();
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ const handleResend = async () => {
await signUp(user.selectedOrganization.serverUrl, email);
}
toast.success('Email sent successfully');
} catch (error: unknown) {
} catch (error) {
toast.error(getErrorMessage(error, 'Error while sending email. Please try again.'));
}
};
Expand Down
4 changes: 2 additions & 2 deletions front-end/src/renderer/components/ForgotPasswordModal.vue
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ async function handleEmailEnter() {

shouldEnterToken.value = true;
setTimeout(() => otpInputRef.value?.focus(), 100);
} catch (error: unknown) {
} catch (error) {
toast.error(getErrorMessage(error, 'Failed to request password reset'));
}
}
Expand All @@ -97,7 +97,7 @@ async function handleTokenEnter() {

shouldEnterToken.value = false;
shouldSetNewPassword.value = true;
} catch (error: unknown) {
} catch (error) {
toast.error(getErrorMessage(error, 'Failed to verify OTP'));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,8 @@ const handleImportExternalKey = async () => {
emit('update:show', false);

toast.success(`${props.keyType} private key imported successfully`);
} catch (err: unknown) {
toast.error(getErrorMessage(err, `Failed to import ${props.keyType} private key`));
} catch (error) {
toast.error(getErrorMessage(error, `Failed to import ${props.keyType} private key`));
}
};

Expand Down
Loading
Loading