Skip to content

Instantly share code, notes, and snippets.

@jln13x
Last active August 15, 2024 16:01
Show Gist options
  • Select an option

  • Save jln13x/dd0361b45e76a57006d94b41d27513e2 to your computer and use it in GitHub Desktop.

Select an option

Save jln13x/dd0361b45e76a57006d94b41d27513e2 to your computer and use it in GitHub Desktop.
export const safeTry = async <T>(
promise: Promise<T>
): Promise<[T, null] | [null, Error]> => {
try {
const data = await promise;
return [data, null];
} catch (throwable) {
if (throwable instanceof Error) return [null, throwable];
throw throwable;
}
};
// Example usage
const [data, error] = await safeTry(getData());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment