Skip to content

Instantly share code, notes, and snippets.

@karlhorky
Last active October 19, 2022 23:43
Show Gist options
  • Save karlhorky/3593d8cd9779cf9313f9852c59260642 to your computer and use it in GitHub Desktop.
Save karlhorky/3593d8cd9779cf9313f9852c59260642 to your computer and use it in GitHub Desktop.
Try-catch helper for promises and async/await
export default async function tryCatch<Data>(
promise: Promise<Data>,
): Promise<{ error: Error } | { data: Data }> {
try {
return { data: await promise };
} catch (error) {
return { error };
}
}
@karlhorky
Copy link
Author

Seems like this may be in TypeScript 4.6, since this PR got merged:

microsoft/TypeScript#46266

@syed-ahmad
Copy link

Thanks @karlhorky

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment