Skip to content

Instantly share code, notes, and snippets.

@moinulmoin
Created March 22, 2025 10:42
Show Gist options
  • Save moinulmoin/fa370c28eccde433b8e26964128bd077 to your computer and use it in GitHub Desktop.
Save moinulmoin/fa370c28eccde433b8e26964128bd077 to your computer and use it in GitHub Desktop.
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;
return [data, null];
} catch (error) {
return [null, error as E];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment