I have dozens of functions with try catch block to handle and log any error occurred.
function add(a, b) {
try {
return a + b;
} catch (error) {
log.error(error.message + ' in add');
}
}
As this try catch statements have same kind of code for each function mentioning error message and the function name in each log, I want some way to avoid writing try catch for each function and want it to be added automatically. My function should be like below one but should work like above one.
function add(a, b) {
return a + b;
}
How could it be possible?
You can wrap your functions up using closures.
For logging, you can try using Function.name, but for meaningful information this rules out arrow functions and otherwise anonymous functions. This could be solved by explicitly passing a name string to the wrap function, but...
There is of course no guarantee the returned function is used via an identifier related to the original name (whatever vs anError below).
const wrap = func => (...args) => {
try {
return func.apply(this, args);
} catch (e) {
console.error(`${e} in ${func.name}`);
}
};
const add = wrap((a, b) => a + b);
const fail = wrap(t => {
if (t)
throw new Error('foo');
});
const whatever = wrap(function anError () {
throw 'an error';
});
console.log(add(1, 2));
fail(false);
fail(true);
whatever();
Combined output:
3
Error: foo in
an error in anError
can you try with callback...
function add(a, b){
return a + b;
}
function substract(a, b){
return a - b;
}
function calc(a){
try{
const f = Array.prototype.shift.apply(arguments);
return f(...arguments);
}catch(e){
console.log(e.stack);
}
}
calc(substract, 1, 2);