functional-try
Version:
Error handling wrapper for cleaner use of strict type checking in TypeScript
64 lines (63 loc) • 1.81 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.tryAsync = exports.trySync = exports.FunctionalTry = void 0;
var FunctionalTry;
(function (FunctionalTry) {
//
// Types
//
//
// Internal utils
//
function createSuccess(value) {
return Object.freeze({
success: true,
failure: false,
value,
error: undefined,
});
}
FunctionalTry.createSuccess = createSuccess;
function createFailure(error) {
return Object.freeze({
success: false,
failure: true,
value: undefined,
error,
});
}
FunctionalTry.createFailure = createFailure;
//
// Public utils
//
/**
* Safely executes a function and returns the resulting value or error
*
* @param func The function to execute
* @param args The arguments to pass to the function
* @returns A `FailableReturn` with the function's return value or thrown error
*/
function trySync(func, ...args) {
try {
return createSuccess(func(...args));
}
catch (error) {
return createFailure(error);
}
}
FunctionalTry.trySync = trySync;
/**
* Wraps a promise and returns the resulting value or error
*
* @param promise The promise to handle
* @returns A `FailableReturn` with the promise's resulting value or error
*/
function tryAsync(promise) {
return promise
.then(createSuccess)
.catch(createFailure);
}
FunctionalTry.tryAsync = tryAsync;
})(FunctionalTry = exports.FunctionalTry || (exports.FunctionalTry = {}));
exports.trySync = FunctionalTry.trySync;
exports.tryAsync = FunctionalTry.tryAsync;