Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
How to write a customised Javascript function

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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
about 4 years ago · Juan Pablo Isaza Report

0

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);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!