Skip to content

Instantly share code, notes, and snippets.

@syed-ahmad
Forked from karlhorky/try-catch.ts
Last active May 6, 2021 16:19
Show Gist options
  • Save syed-ahmad/dc42c8e447b531f7d66ee5520276d36d to your computer and use it in GitHub Desktop.
Save syed-ahmad/dc42c8e447b531f7d66ee5520276d36d to your computer and use it in GitHub Desktop.
Try-catch helper for promises and async/await
// Slightly improved version with destructuring working as expected
export default async function tryCatch<T>(
promise: Promise<T>
): Promise<{ error?: Error; data?: T }> {
try {
return { data: await promise };
} catch (error) {
return { error };
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment