@itsezz/try-catch
Version:
A TypeScript utility for elegant error handling with Result types
238 lines (237 loc) • 8.29 kB
JavaScript
//#region src/index.ts
/*!
* Represents a successful operation result
* @template T The type of the successful data
*/
/*!
* Represents a failed operation result
* @template E The type of the error
*/
/*!
* Union type representing either a successful or failed operation result
* @template T The type of the successful data
* @template E The type of the error, defaults to Error
*/
/*!
* Represents a value that might be a Promise or a direct value
* @template T The type of the value
*/
/*!
* Type guard to check if a result represents a successful operation
*
* @template T The type of the successful data
* @template E The type of the error
* @param result The result to check
* @returns True if the result represents a successful operation
*/
const isSuccess = (result) => {
return result.ok === true;
};
/*!
* Type guard to check if a result represents a failed operation
*
* @template T The type of the successful data
* @template E The type of the error
* @param result The result to check
* @returns True if the result represents a failed operation
*/
const isError = (result) => {
return result.ok === false;
};
/*!
* Creates a success result with the given data
*
* @template T The type of the successful data
* @param data The data to include in the success result
* @returns A Success object containing the data
*/
const success = (data) => {
return {
data,
ok: true
};
};
/*!
* Creates a failure result with the given error
*
* @template E The type of the error
* @param error The error to include in the failure result
* @returns A Failure object containing the error
*/
const failure = (error) => {
return {
error,
ok: false
};
};
/*!
* Transforms the data of a successful result using the provided function
* If the result is a failure, returns the failure unchanged
*
* @template T The type of the original successful data
* @template U The type of the transformed data
* @template E The type of the error
* @param result The result to transform
* @param fn The transformation function
* @returns A new Result with transformed data or the original failure
*/
const map = (result, fn) => {
return isSuccess(result) ? success(fn(result.data)) : result;
};
/*!
* Transforms the data of a successful result using a function that returns a Result
* If the result is a failure, returns the failure unchanged
*
* @template T The type of the original successful data
* @template U The type of the transformed data
* @template E The type of the error
* @param result The result to transform
* @param fn The transformation function that returns a Result
* @returns A new Result with transformed data or a failure
*/
const flatMap = (result, fn) => {
return isSuccess(result) ? fn(result.data) : result;
};
/*!
* Combines multiple results into a single result.
* If all results are successful, returns a success result containing an array of all data.
* If any result is a failure, returns the first failure encountered.
*
* @template T The type of the successful data
* @template E The type of the error
* @param results Array of results to combine
* @returns A Result containing an array of data or the first failure
*/
const all = (results) => {
const data = [];
for (const result of results) {
if (isError(result)) return result;
data.push(result.data);
}
return success(data);
};
/*!
* Extracts the data from a successful result or returns a default value
*
* @template T The type of the successful data
* @template E The type of the error
* @param result The result to unwrap
* @param defaultValue The default value to return if the result is a failure
* @returns The data if successful, otherwise the default value
*/
const unwrapOr = (result, defaultValue) => {
return isSuccess(result) ? result.data : defaultValue;
};
/*!
* Extracts the data from a successful result or computes a default value using the error
*
* @template T The type of the successful data
* @template E The type of the error
* @param result The result to unwrap
* @param fn Function that takes the error and returns a default value
* @returns The data if successful, otherwise the computed default value
*/
const unwrapOrElse = (result, fn) => {
return isSuccess(result) ? result.data : fn(result.error);
};
/*!
* Pattern matching for Result types - handles both success and failure cases
*
* @template T The type of the successful data
* @template E The type of the error
* @template U The return type of both match functions
* @param result The result to match against
* @param handlers Object containing success and failure handler functions
* @returns The result of calling the appropriate handler function
*/
const match = (result, handlers) => {
return isSuccess(result) ? handlers.success(result.data) : handlers.failure(result.error);
};
/*!
* Safely executes a function or awaits a promise, capturing any errors
*
* This utility provides a consistent way to handle both synchronous and asynchronous
* operations that might throw errors. It returns a Result object that can be checked
* with isSuccess, isError, or the ok property.
*
* @template T The type of the successful result
* @template E The type of the error, defaults to unknown
* @param fnOrPromise The function to execute, promise to await, or async function to call
* @returns A Result object for synchronous functions or Promise<Result> for promises and async functions, containing either data or error
*/
function tryCatch(fnOrPromise) {
if (typeof fnOrPromise === "function") try {
const result = fnOrPromise();
if (result instanceof Promise) return result.then((data) => success(data)).catch((error) => failure(error));
return success(result);
} catch (error) {
return failure(error);
}
return fnOrPromise.then((data) => success(data)).catch((error) => failure(error));
}
/*!
* Safely executes a synchronous function, capturing any errors
*
* This utility is specifically for synchronous operations that might throw errors.
* It guarantees a synchronous Result return type, never a Promise.
*
* @template T The type of the successful result
* @template E The type of the error, defaults to unknown
* @param fn The synchronous function to execute
* @returns A Result object containing either data or error
*/
function tryCatchSync(fn) {
try {
return success(fn());
} catch (error) {
return failure(error);
}
}
/*!
* Safely executes an asynchronous function or awaits a promise, capturing any errors
*
* This utility is specifically for asynchronous operations that might throw errors.
* It guarantees a Promise<Result> return type.
*
* @template T The type of the successful result
* @template E The type of the error, defaults to unknown
* @param fnOrPromise The async function to execute or promise to await
* @returns A Promise<Result> containing either data or error
*/
async function tryCatchAsync(fnOrPromise) {
try {
return success(typeof fnOrPromise === "function" ? await fnOrPromise() : await fnOrPromise);
} catch (error) {
return failure(error);
}
}
/*!
* Short alias for tryCatch - safely executes a function or awaits a promise
*
* @template T The type of the successful result
* @template E The type of the error, defaults to unknown
* @param fnOrPromise The function to execute, promise to await, or async function to call
* @returns A Result object for synchronous functions or Promise<Result> for promises and async functions, containing either data or error
*/
const t = tryCatch;
/*!
* Short alias for tryCatchSync - safely executes a synchronous function
*
* @template T The type of the successful result
* @template E The type of the error, defaults to unknown
* @param fn The synchronous function to execute
* @returns A Result object containing either data or error
*/
const tc = tryCatchSync;
/*!
* Short alias for tryCatchAsync - safely executes an async function or awaits a promise
*
* @template T The type of the successful result
* @template E The type of the error, defaults to unknown
* @param fnOrPromise The async function to execute or promise to await
* @returns A Promise<Result> containing either data or error
*/
const tca = tryCatchAsync;
//#endregion
export { all, failure, flatMap, isError, isSuccess, map, match, success, t, tc, tca, tryCatch, tryCatchAsync, tryCatchSync, unwrapOr, unwrapOrElse };
//# sourceMappingURL=index.mjs.map