Skip to content

Instantly share code, notes, and snippets.

@zAlweNy26
Created September 12, 2025 08:48
Show Gist options
  • Save zAlweNy26/3643b1f381541751dd4f52d0617b5202 to your computer and use it in GitHub Desktop.
Save zAlweNy26/3643b1f381541751dd4f52d0617b5202 to your computer and use it in GitHub Desktop.

Revisions

  1. zAlweNy26 created this gist Sep 12, 2025.
    36 changes: 36 additions & 0 deletions tryCatch.ts
    Original 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
    }
    }