Add try-async method

This commit is contained in:
2026-07-19 19:15:22 +00:00
parent 9f0acc1fce
commit 047563f6fa
3 changed files with 86 additions and 0 deletions

15
source/misc.ts Normal file
View File

@@ -0,0 +1,15 @@
/**
* Tries to execute an async function and handles any errors that occur.
* @param fn - The function to execute.
* @param onError - The callback to call if the function fails.
* @returns The result of the function.
*/
export const tryAsync = async (fn: () => unknown, onError?: (error: Error) => void): Promise<void> => {
try {
await fn();
} catch (error) {
const errorInstance = error instanceof Error ? error : new Error(`${error}`);
onError?.(errorInstance);
}
};