'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.



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 PakDragoon