commit 8a3dfc2d623d3cc74d2526d95bd1621ba7dc00ba Author: Leons Aleksandrovs Date: Sun Jul 6 14:10:50 2025 +0300 Add try-catch.ts diff --git a/try-catch.ts b/try-catch.ts new file mode 100644 index 0000000..06b9539 --- /dev/null +++ b/try-catch.ts @@ -0,0 +1,32 @@ +// Types for the result object with discriminated union +type Success = { + data: T; + error: null; +}; + +type Failure = { + data: null; + error: E; +}; + +type Result = Success | Failure; + +// Main wrapper function +export async function tryCatch(promise: Promise): Promise> { + try { + const data = await promise; + return { data, error: null }; + } catch (error) { + return { data: null, error: error as E }; + } +} + +// function for sync +export function tryCatchSync(callback: () => T): Result { + try { + const data = callback(); + return { data, error: null }; + } catch (error) { + return { data: null, error: error as E }; + } +} \ No newline at end of file