Skip to content

Instantly share code, notes, and snippets.

@sstur
Created July 13, 2024 23:37
Show Gist options
  • Save sstur/40e7d5d95b4803d04605ec76ec00f4e7 to your computer and use it in GitHub Desktop.
Save sstur/40e7d5d95b4803d04605ec76ec00f4e7 to your computer and use it in GitHub Desktop.
type Result<T> = [data: T, error: undefined] | [data: undefined, error: Error];
export function noThrow<Args extends Array<unknown>, T>(
fn: (...args: Args) => Promise<T>,
): (...args: Args) => Promise<Result<T>> {
return async (...args) => {
try {
const data = await fn(...args);
return [data, undefined];
} catch (e) {
const error = e instanceof Error ? e : new Error(String(e));
return [undefined, error];
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment