Last active
October 6, 2025 07:24
-
-
Save devzom/5cecb238c45697bfd938056eee1129e5 to your computer and use it in GitHub Desktop.
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
| // Utility function for try-catch, | |
| // handle promises, where error is always of type Error. | |
| // The function returns tuple [data, error], where data is result of promise and error is error if promise is rejected. | |
| // Usage: | |
| // const [productData, productError] = await tryCatch(getProduct(1)) | |
| // if (error) throw new Error(productError.message || 'Cannot get product data', {cause: productError}) | |
| // else console.log(data) | |
| type SuccessResults<T> = readonly [T, null] | |
| type ErrorResults<E = Error> = readonly [null, E] | |
| type Result<T, E = Error> = SuccessResults<T> | ErrorResults<E> | |
| export const tryCatch = async <T, E = Error>(promise: Promise<T>): Promise<Result<T, E>> => { | |
| try { | |
| const data = await promise; | |
| return [data, null] as const; | |
| } catch (error) { | |
| return [null, error as E] as const; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment