Skip to content

Instantly share code, notes, and snippets.

@nbbaier
Forked from t3dotgg/try-catch.ts
Created April 22, 2025 17:02
Show Gist options
  • Save nbbaier/c47eea92583bd23e3ccf6dbcfe6adbf0 to your computer and use it in GitHub Desktop.
Save nbbaier/c47eea92583bd23e3ccf6dbcfe6adbf0 to your computer and use it in GitHub Desktop.

Revisions

  1. @t3dotgg t3dotgg revised this gist Feb 24, 2025. 1 changed file with 0 additions and 8 deletions.
    8 changes: 0 additions & 8 deletions try-catch.ts
    Original file line number Diff line number Diff line change
    @@ -21,12 +21,4 @@ export async function tryCatch<T, E = Error>(
    } catch (error) {
    return { data: null, error: error as E };
    }
    }

    async function somePromise() {
    const response = await fetch("https://api.example.com/data");
    if (!response.ok) {
    throw new Error("Network response was not ok");
    }
    return (await response.json()) as { username: string };
    }
  2. @t3dotgg t3dotgg created this gist Feb 24, 2025.
    32 changes: 32 additions & 0 deletions try-catch.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    // Types for the result object with discriminated union
    type Success<T> = {
    data: T;
    error: null;
    };

    type Failure<E> = {
    data: null;
    error: E;
    };

    type Result<T, E = Error> = Success<T> | Failure<E>;

    // Main wrapper function
    export async function tryCatch<T, E = Error>(
    promise: Promise<T>,
    ): Promise<Result<T, E>> {
    try {
    const data = await promise;
    return { data, error: null };
    } catch (error) {
    return { data: null, error: error as E };
    }
    }

    async function somePromise() {
    const response = await fetch("https://api.example.com/data");
    if (!response.ok) {
    throw new Error("Network response was not ok");
    }
    return (await response.json()) as { username: string };
    }