Last active
March 2, 2025 08:18
-
-
Save yazaldefilimone/89480a75ac0bded267b0251d655682f4 to your computer and use it in GitHub Desktop.
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 characters
// result: https://gist.github.com/yazaldefilimone/b1d3749def942013ee5128161837432e | |
import { Err, Ok, type Result } from "~/utils/result"; | |
export async function safeAsync<T>(asyncFn: () => Promise<T>): Promise<Result<T, Error>> { | |
try { | |
const result = await asyncFn(); | |
return Ok(result); | |
} catch (error) { | |
return Err(normalizeError(error)); | |
} | |
} | |
export function wrapAsync<F extends (...args: any[]) => Promise<any>>(asyncFn: F) { | |
return async (...args: Parameters<F>): Promise<Result<Awaited<ReturnType<F>>, Error>> => { | |
try { | |
const result = await asyncFn(...args); | |
return Ok(result); | |
} catch (e: unknown) { | |
return Err(normalizeError(e)); | |
} | |
}; | |
} | |
function normalizeError(error: unknown): Error { | |
if (error instanceof Error) return error; | |
if (typeof error === "string") return new Error(error); | |
return new Error("An unknown error occurred"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment