UNPKG

@itsezz/try-catch

Version:

A TypeScript utility for elegant error handling with Result types

1 lines 12.4 kB
{"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/*!\r\n * Represents a successful operation result\r\n * @template T The type of the successful data\r\n */\r\nexport type Success<T> = {\r\n\tdata: T;\r\n\terror?: never;\r\n\treadonly ok: true;\r\n};\r\n\r\n/*!\r\n * Represents a failed operation result\r\n * @template E The type of the error\r\n */\r\nexport type Failure<E> = {\r\n\tdata?: never;\r\n\terror: E;\r\n\treadonly ok: false;\r\n};\r\n\r\n/*!\r\n * Union type representing either a successful or failed operation result\r\n * @template T The type of the successful data\r\n * @template E The type of the error, defaults to Error\r\n */\r\nexport type Result<T, E = Error> = Success<T> | Failure<E>;\r\n\r\n/*!\r\n * Represents a value that might be a Promise or a direct value\r\n * @template T The type of the value\r\n */\r\nexport type MaybePromise<T> = T | Promise<T>;\r\n\r\n/*!\r\n * Type guard to check if a result represents a successful operation\r\n *\r\n * @template T The type of the successful data\r\n * @template E The type of the error\r\n * @param result The result to check\r\n * @returns True if the result represents a successful operation\r\n */\r\nexport const isSuccess = <T, E>(result: Result<T, E>): result is Success<T> => {\r\n\treturn result.ok === true;\r\n};\r\n\r\n/*!\r\n * Type guard to check if a result represents a failed operation\r\n *\r\n * @template T The type of the successful data\r\n * @template E The type of the error\r\n * @param result The result to check\r\n * @returns True if the result represents a failed operation\r\n */\r\nexport const isError = <T, E>(result: Result<T, E>): result is Failure<E> => {\r\n\treturn result.ok === false;\r\n};\r\n\r\n/*!\r\n * Creates a success result with the given data\r\n *\r\n * @template T The type of the successful data\r\n * @param data The data to include in the success result\r\n * @returns A Success object containing the data\r\n */\r\nexport const success = <T>(data: T): Success<T> => {\r\n\treturn { data, ok: true };\r\n};\r\n\r\n/*!\r\n * Creates a failure result with the given error\r\n *\r\n * @template E The type of the error\r\n * @param error The error to include in the failure result\r\n * @returns A Failure object containing the error\r\n */\r\nexport const failure = <E>(error: E): Failure<E> => {\r\n\treturn { error, ok: false };\r\n};\r\n\r\n/*!\r\n * Transforms the data of a successful result using the provided function\r\n * If the result is a failure, returns the failure unchanged\r\n *\r\n * @template T The type of the original successful data\r\n * @template U The type of the transformed data\r\n * @template E The type of the error\r\n * @param result The result to transform\r\n * @param fn The transformation function\r\n * @returns A new Result with transformed data or the original failure\r\n */\r\nexport const map = <T, U, E>(result: Result<T, E>, fn: (data: T) => U): Result<U, E> => {\r\n\treturn isSuccess(result) ? success(fn(result.data)) : result;\r\n};\r\n\r\n/*!\r\n * Transforms the data of a successful result using a function that returns a Result\r\n * If the result is a failure, returns the failure unchanged\r\n *\r\n * @template T The type of the original successful data\r\n * @template U The type of the transformed data\r\n * @template E The type of the error\r\n * @param result The result to transform\r\n * @param fn The transformation function that returns a Result\r\n * @returns A new Result with transformed data or a failure\r\n */\r\nexport const flatMap = <T, U, E>(result: Result<T, E>, fn: (data: T) => Result<U, E>): Result<U, E> => {\r\n\treturn isSuccess(result) ? fn(result.data) : result;\r\n};\r\n\r\n/*!\r\n * Combines multiple results into a single result.\r\n * If all results are successful, returns a success result containing an array of all data.\r\n * If any result is a failure, returns the first failure encountered.\r\n *\r\n * @template T The type of the successful data\r\n * @template E The type of the error\r\n * @param results Array of results to combine\r\n * @returns A Result containing an array of data or the first failure\r\n */\r\nexport const all = <T, E>(results: Result<T, E>[]): Result<T[], E> => {\r\n\tconst data: T[] = [];\r\n\tfor (const result of results) {\r\n\t\tif (isError(result)) return result;\r\n\t\tdata.push(result.data);\r\n\t}\r\n\treturn success(data);\r\n};\r\n\r\n/*!\r\n * Extracts the data from a successful result or returns a default value\r\n *\r\n * @template T The type of the successful data\r\n * @template E The type of the error\r\n * @param result The result to unwrap\r\n * @param defaultValue The default value to return if the result is a failure\r\n * @returns The data if successful, otherwise the default value\r\n */\r\nexport const unwrapOr = <T, E>(result: Result<T, E>, defaultValue: T): T => {\r\n\treturn isSuccess(result) ? result.data : defaultValue;\r\n};\r\n\r\n/*!\r\n * Extracts the data from a successful result or computes a default value using the error\r\n *\r\n * @template T The type of the successful data\r\n * @template E The type of the error\r\n * @param result The result to unwrap\r\n * @param fn Function that takes the error and returns a default value\r\n * @returns The data if successful, otherwise the computed default value\r\n */\r\nexport const unwrapOrElse = <T, E>(result: Result<T, E>, fn: (error: E) => T): T => {\r\n\treturn isSuccess(result) ? result.data : fn(result.error);\r\n};\r\n\r\n/*!\r\n * Pattern matching for Result types - handles both success and failure cases\r\n *\r\n * @template T The type of the successful data\r\n * @template E The type of the error\r\n * @template U The return type of both match functions\r\n * @param result The result to match against\r\n * @param handlers Object containing success and failure handler functions\r\n * @returns The result of calling the appropriate handler function\r\n */\r\nexport const match = <T, E, U>(\r\n\tresult: Result<T, E>,\r\n\thandlers: {\r\n\t\tsuccess: (data: T) => U;\r\n\t\tfailure: (error: E) => U;\r\n\t},\r\n): U => {\r\n\treturn isSuccess(result) ? handlers.success(result.data) : handlers.failure(result.error);\r\n};\r\n\r\n/*!\r\n * Safely executes a function or awaits a promise, capturing any errors\r\n *\r\n * This utility provides a consistent way to handle both synchronous and asynchronous\r\n * operations that might throw errors. It returns a Result object that can be checked\r\n * with isSuccess, isError, or the ok property.\r\n *\r\n * @template T The type of the successful result\r\n * @template E The type of the error, defaults to unknown\r\n * @param fnOrPromise The function to execute, promise to await, or async function to call\r\n * @returns A Result object for synchronous functions or Promise<Result> for promises and async functions, containing either data or error\r\n */\r\nexport function tryCatch<T, E = unknown>(fn: () => Promise<T>): Promise<Result<T, E>>;\r\nexport function tryCatch<T, E = unknown>(fn: () => T): Result<T, E>;\r\nexport function tryCatch<T, E = unknown>(promise: Promise<T>): Promise<Result<T, E>>;\r\nexport function tryCatch<T, E = unknown>(\r\n\tfnOrPromise: Promise<T> | (() => MaybePromise<T>),\r\n): Result<T, E> | Promise<Result<T, E>> {\r\n\tif (typeof fnOrPromise === 'function') {\r\n\t\ttry {\r\n\t\t\tconst result = fnOrPromise();\r\n\r\n\t\t\tif (result instanceof Promise) {\r\n\t\t\t\treturn result.then((data) => success(data)).catch((error) => failure(error as E));\r\n\t\t\t}\r\n\r\n\t\t\treturn success(result);\r\n\t\t} catch (error) {\r\n\t\t\treturn failure(error as E);\r\n\t\t}\r\n\t}\r\n\r\n\treturn fnOrPromise.then((data) => success(data)).catch((error) => failure(error as E));\r\n}\r\n\r\n/*!\r\n * Safely executes a synchronous function, capturing any errors\r\n *\r\n * This utility is specifically for synchronous operations that might throw errors.\r\n * It guarantees a synchronous Result return type, never a Promise.\r\n *\r\n * @template T The type of the successful result\r\n * @template E The type of the error, defaults to unknown\r\n * @param fn The synchronous function to execute\r\n * @returns A Result object containing either data or error\r\n */\r\nexport function tryCatchSync<T, E = unknown>(fn: () => T): Result<T, E> {\r\n\ttry {\r\n\t\tconst result = fn();\r\n\t\treturn success(result);\r\n\t} catch (error) {\r\n\t\treturn failure(error as E);\r\n\t}\r\n}\r\n\r\n/*!\r\n * Safely executes an asynchronous function or awaits a promise, capturing any errors\r\n *\r\n * This utility is specifically for asynchronous operations that might throw errors.\r\n * It guarantees a Promise<Result> return type.\r\n *\r\n * @template T The type of the successful result\r\n * @template E The type of the error, defaults to unknown\r\n * @param fnOrPromise The async function to execute or promise to await\r\n * @returns A Promise<Result> containing either data or error\r\n */\r\nexport async function tryCatchAsync<T, E = unknown>(fn: () => Promise<T>): Promise<Result<T, E>>;\r\nexport async function tryCatchAsync<T, E = unknown>(promise: Promise<T>): Promise<Result<T, E>>;\r\nexport async function tryCatchAsync<T, E = unknown>(\r\n\tfnOrPromise: Promise<T> | (() => Promise<T>),\r\n): Promise<Result<T, E>> {\r\n\ttry {\r\n\t\tconst data = typeof fnOrPromise === 'function' ? await fnOrPromise() : await fnOrPromise;\r\n\t\treturn success(data);\r\n\t} catch (error) {\r\n\t\treturn failure(error as E);\r\n\t}\r\n}\r\n\r\n/*!\r\n * Short alias for tryCatch - safely executes a function or awaits a promise\r\n *\r\n * @template T The type of the successful result\r\n * @template E The type of the error, defaults to unknown\r\n * @param fnOrPromise The function to execute, promise to await, or async function to call\r\n * @returns A Result object for synchronous functions or Promise<Result> for promises and async functions, containing either data or error\r\n */\r\nexport const t = tryCatch;\r\n\r\n/*!\r\n * Short alias for tryCatchSync - safely executes a synchronous function\r\n *\r\n * @template T The type of the successful result\r\n * @template E The type of the error, defaults to unknown\r\n * @param fn The synchronous function to execute\r\n * @returns A Result object containing either data or error\r\n */\r\nexport const tc = tryCatchSync;\r\n\r\n/*!\r\n * Short alias for tryCatchAsync - safely executes an async function or awaits a promise\r\n *\r\n * @template T The type of the successful result\r\n * @template E The type of the error, defaults to unknown\r\n * @param fnOrPromise The async function to execute or promise to await\r\n * @returns A Promise<Result> containing either data or error\r\n */\r\nexport const tca = tryCatchAsync;\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAa,aAAmB,WAA+C;CAC9E,OAAO,OAAO,OAAO;AACtB;;;;;;;;;AAUA,MAAa,WAAiB,WAA+C;CAC5E,OAAO,OAAO,OAAO;AACtB;;;;;;;;AASA,MAAa,WAAc,SAAwB;CAClD,OAAO;EAAE;EAAM,IAAI;CAAK;AACzB;;;;;;;;AASA,MAAa,WAAc,UAAyB;CACnD,OAAO;EAAE;EAAO,IAAI;CAAM;AAC3B;;;;;;;;;;;;AAaA,MAAa,OAAgB,QAAsB,OAAqC;CACvF,OAAO,UAAU,MAAM,IAAI,QAAQ,GAAG,OAAO,IAAI,CAAC,IAAI;AACvD;;;;;;;;;;;;AAaA,MAAa,WAAoB,QAAsB,OAAgD;CACtG,OAAO,UAAU,MAAM,IAAI,GAAG,OAAO,IAAI,IAAI;AAC9C;;;;;;;;;;;AAYA,MAAa,OAAa,YAA4C;CACrE,MAAM,OAAY,CAAC;CACnB,KAAK,MAAM,UAAU,SAAS;EAC7B,IAAI,QAAQ,MAAM,GAAG,OAAO;EAC5B,KAAK,KAAK,OAAO,IAAI;CACtB;CACA,OAAO,QAAQ,IAAI;AACpB;;;;;;;;;;AAWA,MAAa,YAAkB,QAAsB,iBAAuB;C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