Skip to content

Instantly share code, notes, and snippets.

@alexsasharegan
Created January 28, 2018 20:27
Show Gist options
  • Save alexsasharegan/04a038f66cf38090eeb68cca12af55e4 to your computer and use it in GitHub Desktop.
Save alexsasharegan/04a038f66cf38090eeb68cca12af55e4 to your computer and use it in GitHub Desktop.
Type safe error handling for javascript promises.
type Result<T> =
| {
ok: true
value: T
}
| {
ok: false
error: any
}
export async function WrapErr<T>(p: Promise<T>): Promise<Result<T>> {
try {
return {
ok: true,
value: await p,
}
} catch (error) {
return {
ok: false,
error,
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment