UNPKG

@shkumbinhsn/try-catch

Version:

A utility package for handling try-catch blocks in TypeScript with full type inference.

54 lines 1.51 kB
const errorSymbol = Symbol(); /** * Executes a function within a try-catch block and returns a tuple [data, error]. * * @param fn - The function to execute. Can be synchronous or return a Promise. * @returns A tuple where: * - For success: [data, null] where data is the function's return value * - For failure: [null, error] where error is the caught exception * * @example * // Synchronous usage * const [data, error] = tryCatch(() => riskyFunction()); * * @example * // Asynchronous usage * const [data, error] = await tryCatch(() => asyncRiskyFunction()); */ export function tryCatch(fn) { try { const result = fn(); if (result instanceof Promise) { return new Promise((resolve) => { result .then((data) => resolve([data, null])) .catch((error) => resolve([null, error])); }); } return [result, null]; } catch (e) { return [null, e]; } } /** * Brands a return value with potential error types for tryCatch inference. * Uses a fluent API for declaring errors. * * @param value - The value to return * @returns A builder with mightThrow() to declare error types * * @example * function fetchUser() { * const user = getUser(); * return tc(user).mightThrow<APIError | NetworkError>(); * } */ export function tc(value) { return { mightThrow() { return value; }, }; } //# sourceMappingURL=index.js.map