Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

170
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda