feat(utils): added in trycatch function

This commit is contained in:
2025-12-22 20:28:37 -06:00
parent 797c9ccdf4
commit 5995650d67
2 changed files with 42 additions and 2 deletions

View File

@@ -0,0 +1,28 @@
type Success<T> = { data: T; error: null };
type Failure<E> = { data: null; error: E };
export type Result<T, E = Error> = Success<T> | Failure<E>;
/**
* A universal tryCatch wrapper that:
* - Never throws
* - Always resolves to Result<T,E>
* - Allows optional error mapping function for strong typing
*/
export async function tryCatch<T, E = Error>(
promise: Promise<T>,
onError?: (error: unknown) => E,
): Promise<Result<T, E>> {
try {
const data = await promise;
return { data, error: null };
} catch (err: unknown) {
const error = onError
? onError(err)
: err instanceof Error
? (err as E)
: (new Error(String(err)) as E);
return { data: null, error };
}
}