Last active
May 25, 2025 02:00
-
-
Save psenger/bb95407a26fc994bb3c9cc7efcd41400 to your computer and use it in GitHub Desktop.
[Design Pattern: A better Try-Catch] #JavaScript #Promise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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