Skip to content

Instantly share code, notes, and snippets.

@jsynowiec
Created February 18, 2025 09:35
Show Gist options
  • Save jsynowiec/d66a072d4f113915015aedc4e9cfdd2e to your computer and use it in GitHub Desktop.
Save jsynowiec/d66a072d4f113915015aedc4e9cfdd2e to your computer and use it in GitHub Desktop.
go-lang like pattern for cleaner error handling with async/await
function catcher<T = any, E = Error> (
promise: Promise<T>
): Promise<[T | undefined, E | null]> {
return promise
.then<[T, null]>((data: T) => [data, null])
.catch<[undefined, E]>((err: E) => {
return [undefined, err];
});
}
// Example
// const [err, result] = await catcher(someFunctio())
// if (err) { ... }
// Reference
// https://go.dev/blog/error-handling-and-go
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment