Created
May 3, 2023 15:02
-
-
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.
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 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 }; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Same example as in snippet, but with syntax highlighting ;)