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

200
Vistas
How to handle errors asynchronously in NodeJS

I am trying to handle errors in NodeJS service which I need them next in the logging. The code I wrote is working fine but I am wondering if it is the best way to handle errors or there is a best practice to do that.

route.js

router.get('/mails', async (req, res, next) => {

  try {
    let reqBodydata = fs.readFileSync('./api/soap_request/mail/mail.json');
    const requestBody = JSON.parse(reqBodydata);
    soap.createClient(url, function (err, client) {
      try {
        if (err) {
          throw new ServerError({
            status: err.status,
            error: err.body
          });
        }
        client.mail(requestBody, async function (err, response) {
          try {
            if (err) {
              throw new ServerError({
                status: err.status,
                error: err.body
              });
            }
            const result = await mySrv.getEmails(response);
            res.status(result.status || 200).send(result.data);
          }
          catch (err) {
            next(err);
          }
        });
      }
      catch (err) {
        next(err);
      }
    });
  } catch (err) {
    next(err);
  }
});

server.js

// catch errors
app.use((err, req, res, next) => {
  const status = err.status || 500;
  const msg = err.error || err.message;
  logging.logError(`Error ${status} (${msg}) on ${req.method} ${req.url} with payload ${req.body}.`,'',correlator.getId());
  res.status(status).send({ status, error: msg });
});

Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You should only use promises for async functions and try/catch for sync functions in my opinion.

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