Skip to content

Instantly share code, notes, and snippets.

@psenger
Last active May 25, 2025 02:00
Show Gist options
  • Save psenger/bb95407a26fc994bb3c9cc7efcd41400 to your computer and use it in GitHub Desktop.
Save psenger/bb95407a26fc994bb3c9cc7efcd41400 to your computer and use it in GitHub Desktop.
[Design Pattern: A better Try-Catch] #JavaScript #Promise
// Based on Theo - t3․gg suggestion and ZOD
// Youtube https://www.youtube.com/watch?v=Y6jT-IkV0VM&t=538s
// and gist https://gist.github.com/t3dotgg/a486c4ae66d32bf17c09c73609dacc5b
type Success<T> = {
success: true
data: T
error?: never
}
type Failure<E> = {
success: false
data?: never
error: E
};
type SafeResult<T, E = Error> = Success<T> | Failure<E>
export async function tryCatch<T, E = Error>(fn: Promise<T> | (() => T)): Promise<SafeResult<T, E>> {
try {
let data: T;
if (typeof fn === 'function') {
data = fn();
} else {
data = await fn;
}
return { data, success: true };
} catch (error) {
return { error: error as E, success: false };
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment