Last active
April 22, 2025 12:14
-
-
Save zzzarius/58e1fe38081835cb1f83903619336009 to your computer and use it in GitHub Desktop.
Cleaner error handling using `never throw` pattern
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
type OK<T> = { | |
data: T | |
err: null | |
} | |
type Fail<E> = { | |
data: null | |
err: E | |
} | |
type Result<T, E = Error> = OK<T> | Fail<E> | |
export async function neverThrow<T, E = Error>( | |
promise: Promise<T>, | |
): Promise<Result<T, E>> { | |
try { | |
const data = await promise | |
return { data, err: null } | |
} catch (error) { | |
return { data: null, err: error as E } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment