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

197
Views
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 answers
Answer question

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 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!