Skip to content

Instantly share code, notes, and snippets.

@metruzanca
Created May 3, 2023 15:02
Show Gist options
  • Save metruzanca/1f2a734e1729e83ef38ae6937ef1a31c to your computer and use it in GitHub Desktop.
Save metruzanca/1f2a734e1729e83ef38ae6937ef1a31c to your computer and use it in GitHub Desktop.
Inspired by Golang's error handling, using typescript's to provide a type safety without try-catch blocks.
type Error = { type: 'error'; error: any; };
type Success<R> = { type: 'success'; data: R; };
/**
* No more try catch blocks
*
* Inspired by {@link [Golang's error handling](https://gabrieltanner.org/blog/golang-error-handling-definitive-guide)}
* using typescript's {@link [narrowing](https://www.typescriptlang.org/docs/handbook/2/narrowing.html)}
* to provide a type-safe DX.
*
* @example
* const response = await go(fetch(`api/user/${id}`))
* if (response.type === 'error') {
* console.error(response.error)
* return;
* }
* console.log(response.data) // No type error claiming that data might be null
*/
export default async function go<R = any>(promise: Promise<R>): Promise<Error | Success<R>> {
try {
const data = await promise;
return { type: 'success', data };
} catch (error) {
return { type: 'error', error };
}
}
@metruzanca
Copy link
Author

Same example as in snippet, but with syntax highlighting ;)

 const response = await go(fetch(`api/user/${id}`))
 if (response.type === 'error') {
  console.error(response.error)
  return;
 }
 console.log(response.data) // No type error claiming that data might be null

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment