Created
March 22, 2025 10:42
-
-
Save moinulmoin/fa370c28eccde433b8e26964128bd077 to your computer and use it in GitHub Desktop.
Go like error handling for promises in TS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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