Created
February 18, 2025 09:35
-
-
Save jsynowiec/d66a072d4f113915015aedc4e9cfdd2e to your computer and use it in GitHub Desktop.
go-lang like pattern for cleaner error handling with async/await
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
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