Skip to content

Instantly share code, notes, and snippets.

@nthung2112
Last active May 24, 2025 04:58
Show Gist options
  • Save nthung2112/39649902bc1b02004faef435d9575dfb to your computer and use it in GitHub Desktop.
Save nthung2112/39649902bc1b02004faef435d9575dfb to your computer and use it in GitHub Desktop.
Error Try Catch
// /utils/result.ts
export type Failure<E> = {
success: false;
error: E;
};
function Failure<E>(error: E): Failure<E> {
return {
success: false,
error,
};
}
export type Success<T> = {
success: true;
value: T;
};
function Success<T>(value: T): Success<T> {
return {
success: true,
value,
};
}
export type Result<T, E = never> = Success<T> | Failure<E>;
export const Result = {
Failure,
Success,
};
export const tryCatch = async <T>(
fn: () => Promise<T>,
logError = false
): Promise<[T | undefined, Error | undefined]> => {
try {
const data = await fn();
return [data, undefined];
} catch (error: unknown) {
const err = error instanceof Error ? error : new Error(String(error));
if (logError) {
console.error(err);
}
return [undefined, err];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment