Skip to content

Instantly share code, notes, and snippets.

@mheob
Last active March 24, 2025 15:39
Show Gist options
  • Save mheob/243cf35e3a4cc7cd9969f2933a2498a9 to your computer and use it in GitHub Desktop.
Save mheob/243cf35e3a4cc7cd9969f2933a2498a9 to your computer and use it in GitHub Desktop.
Wraps a promise in a try-catch block, so it helps with handling async operations in a more declarative way.
type Success<T> = {
data: T;
error: null;
};
type Failure<E> = {
data: null;
error: E;
};
type Result<T, E = Error> = Success<T> | Failure<E>;
/**
* Wraps a promise in a try-catch block and returns a `{ data, error }` object.
* Helps with handling async operations in a more declarative way.
*
* So instead of writing
*
* ```typescript
* try {
* const data = await promise;
* return { data, error: null };
* } catch (error) {
* return { data: null, error: "Something went wrong!" };
* }
* ```
*
* you can use it like this:
*
* ```typescript
* function getData() {
* const { data, error } = await tryCatch(promise);
*
* if (error) return { data: null, error: "Something went wrong!"}
* return { data, error: null };
* }
* ```
*
* @param promise the promise to check
* @returns a `{ data, error }` object
*/
export async function tryCatch<T, E = Error>(promise: Promise<T>): Promise<Result<T, E>> {
try {
const data = await promise;
return { data, error: null };
} catch (error) {
return { data: null, error: error as E };
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment