Skip to content

Instantly share code, notes, and snippets.

@zzzarius
Last active April 22, 2025 12:14
Show Gist options
  • Save zzzarius/58e1fe38081835cb1f83903619336009 to your computer and use it in GitHub Desktop.
Save zzzarius/58e1fe38081835cb1f83903619336009 to your computer and use it in GitHub Desktop.
Cleaner error handling using `never throw` pattern
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