Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda