utils
Code

tryCatch

Executes code with error handling, allowing custom recovery or fallback actions.

Code

try-catch.ts
type SuccessResult<T> = readonly [T, null];
type ErrorResult<E = Error> = readonly [null, E];
 
type Result<T, E = Error> = SuccessResult<T> | ErrorResult<E>;
 
export async function tryCatch<T, E = Error>(
  promise: Promise<T>
): Promise<Result<T, E>> {
  try {
    const data = await promise;
    return [data, null] as const;
  } catch (error) {
    return [null, error as E] as const;
  }
}

Example

const [user, error] = await tryCatch(getUser("399500438002597888"));
 
if (error) return console.error("failed to fetch user!");
 
console.log(user);

On this page