trywrap
Version:
A utility module to handle async function errors gracefully.
44 lines (37 loc) • 1.61 kB
JavaScript
const trywrap = require("./index");
async function testFn(value, a, b) {
if (value < 0) throw new Error("Negative value");
return `Success: ${value}, ${a}, ${b}`;
}
onError = ({ error, methodName, args }) => {
console.error(`Caught in ${methodName} with args ${JSON.stringify(args)}:`, error.message);
};
(async () => {
// Test: should return the result of the async function when no error occurs
const result1 = await trywrap(testFn, [10, 20, 30], {
onError,
fallback: "Default Value"
});
console.log(result1 === 'Success: 10, 20, 30' ? 'Test passed' : 'Test failed');
// Test: should return the fallback value when an error occurs
const result2 = await trywrap(testFn, [-5, 20, 30], {
onError,
fallback: "Default Value"
});
console.log(result2 === 'Default Value' ? 'Test passed' : 'Test failed');
// Test: should skip onError callback and return the fallback value when an error occurs
let errorContext;
const onErrorTest = (context) => {
console.log('onError called with context:', context);
errorContext = context;
};
let context = await trywrap(testFn, [-5, 20, 30], { onError: onErrorTest, fallback: "Default Value" });
console.log(context === 'Default Value' ? 'Test passed' : 'Test failed');
// Test: should rethrow the error if rethrow is true
try {
await trywrap(testFn, [-5, 20, 30], { rethrow: true });
console.log('Test failed');
} catch (error) {
console.log(error.message === 'Negative value' ? 'Test passed' : 'Test failed');
}
})();