@augment-vir/common
Version:
A collection of augments, helpers types, functions, and classes for any JavaScript environment.
99 lines (98 loc) • 2.65 kB
JavaScript
import { check } from '@augment-vir/assert';
import { ensureError, } from '@augment-vir/core';
/**
* Calls the callback and returns its output. If the callback throws an error, it is handled in the
* following ways:
*
* - If a `handleError` function is provided in `options`, it is passed the thrown error. The output
* of `handleError` is returned by `wrapInTry`.
* - If a `fallbackValue` is provided, it is returned by `wrapInTry`. The thrown error is ignored.
* - If no options are provided, the thrown error is returned by `wrapInTry`.
*
* @category Function
* @category Package : @augment-vir/common
* @example
*
* ```ts
* import {wrapInTry} from '@augment-vir/common';
*
* // `result1` will be `'success'`.
* const result1 = wrapInTry(
* () => {
* return 'success';
* },
* {
* fallbackValue: 'failure',
* },
* );
* // `result2` will be `'failure'`.
* const result2 = wrapInTry(
* () => {
* throw new Error();
* return 'success';
* },
* {
* fallbackValue: 'failure',
* },
* );
* // `result3` will be `'failure also'`.
* const result3 = wrapInTry(
* () => {
* throw new Error();
* return 'success';
* },
* {
* handleError() {
* return 'failure also';
* },
* },
* );
* // `result4` will be `'failure also'`.
* const result4 = wrapInTry(
* () => {
* throw new Error();
* return 'success';
* },
* {
* handleError() {
* return 'failure also';
* },
* fallbackValue: 'ignored',
* },
* );
* ```
*
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common)
*/
export function wrapInTry(callback, options = {}) {
try {
const value = callback();
if (value instanceof Promise) {
return value.catch((error) => {
if (options.handleError) {
return options.handleError(error);
}
else if (check.hasKey(options, 'fallbackValue')) {
return options.fallbackValue;
}
else {
return ensureError(error);
}
});
}
else {
return value;
}
}
catch (error) {
if (options.handleError) {
return options.handleError(error);
}
else if (check.hasKey(options, 'fallbackValue')) {
return options.fallbackValue;
}
else {
return ensureError(error);
}
}
}