Created
September 12, 2025 08:48
-
-
Save zAlweNy26/3643b1f381541751dd4f52d0617b5202 to your computer and use it in GitHub Desktop.
Revisions
-
zAlweNy26 created this gist
Sep 12, 2025 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,36 @@ /** * Catches errors from a promise. * @param promise The promise to handle. * @param options Additional options for handling the promise. * @returns A tuple with either the error or the result of the promise. * @throws Will rethrow the error if it is not in the `errorsToCatch` array. */ export async function tryCatch<T = any, E extends new (...args: any[]) => Error = ErrorConstructor>( promise: Promise<T>, options?: { /** An optional array of error constructors to catch */ errorsToCatch?: E[] /** An optional message to log when an error occurs */ logMessage?: string /** A callback function to execute on success */ onSuccess?: (result: T) => void /** A callback function to execute on error */ onError?: (error: E) => void }, ): Promise<[undefined, T] | [InstanceType<E>]> { const { errorsToCatch, logMessage, onError, onSuccess } = options ?? {} try { const res = await promise onSuccess?.(res) return [undefined, res] } catch (error: any) { if (errorsToCatch === undefined || errorsToCatch.some(e => error instanceof e)) { console.error(logMessage || 'An error occurred while executing a promise:') console.dir(error) onError?.(error) return [error] } throw error } }