Skip to content

Instantly share code, notes, and snippets.

View moinulmoin's full-sized avatar
👀
Available for collaboration

Moinul Moin moinulmoin

👀
Available for collaboration
View GitHub Profile
@moinulmoin
moinulmoin / try-catch.ts
Created March 22, 2025 10:42
Go like error handling for promises in TS
/**
* Wraps a promise and returns a tuple where the first element is the data if successful,
* or null if an error occurred, and the second element is the error if any, or null if successful.
*
* @param promise The promise to wrap.
* @returns A promise that resolves to [data, null] on success or [null, error] on failure.
*/
export async function tryCatch<T, E = Error>(promise: Promise<T>): Promise<[T, null] | [null, E]> {
try {
const data = await promise;