Skip to content

Instantly share code, notes, and snippets.

@devzom
Last active October 6, 2025 07:24
Show Gist options
  • Save devzom/5cecb238c45697bfd938056eee1129e5 to your computer and use it in GitHub Desktop.
Save devzom/5cecb238c45697bfd938056eee1129e5 to your computer and use it in GitHub Desktop.
// 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