trywrap
Version:
A utility module to handle async function errors gracefully.
36 lines (33 loc) • 1.34 kB
JavaScript
/**
* Executes an async function and catches any errors, providing a fallback value or rethrowing the error.
*
* @template T
* @param {Function} asyncFunction - The async function to execute.
* @param {Array} [args=[]] - The arguments to pass to the function.
* @param {Object} [options={}] - Options for error handling.
* @param {Function} [options.onError] - A callback function to handle errors.
* @param {T} [options.fallback] - A fallback value to return in case of an error.
* @param {boolean} [options.rethrow] - If true, rethrows the error after calling onError.
* @returns {Promise<T>} - The result of the function or the fallback value.
*/
async function trywrap(asyncFunction, args = [], options = {}) {
// Set rethrow to true by default if not provided
const { onError, fallback, rethrow = true } = options;
try {
return await asyncFunction(...args);
} catch (error) {
if ('fallback' in options) return fallback;
if (onError && typeof onError === 'function') {
const errorContext = {
error,
methodName: asyncFunction.name || 'anonymous function',
args
};
return onError(errorContext);
}
if (rethrow) {
throw error;
}
}
}
module.exports = trywrap;