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

68
Views
Try-Catch Not Handling Errors Properly

I have this try-catch block which is supposed to catch any errors encountered while connecting to a Mongo Database, and return the status of "Unauthorised". However, Express crashes in the backend although I am handling the errors if I turn off the MongoDB engine for testing. Shouldn't the errors be handled properly? (I am not using the err code as of now for testing.)

app.post('/api/login', (req, res) => {
  id = req.body.account
  var query = {_id: id}
  try {
    db.collection("Users").findOne(query, (err, result) => {
      if (result) {
        nonce = noncef()
        var upvalues = { $set: {nonce: nonce} }
        db.collection("Users").updateOne(query, upvalues, (err, result) => {
          if (result) {
            res.send(`${nonce}`)
          }
        })
      }
    })
  }
  catch(err) {
    res.status(401).send('Unauthorized')
  }
})
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Use Promises for .findOne and .updateOne instead of callbacks, and then you can await the results (and catch them), or chain a .catch onto the Promise chain.

app.post('/api/login', async (req, res) => {
    const query = { _id: req.body.account }
    try {
        const user = await db.collection("Users").findOne(query);
        if (!user) return;
        const nonce = noncef();
        const upvalues = { $set: { nonce } };
        const updated = await db.collection("Users").updateOne(query, upvalues);
        if (updated) res.send(nonce);
    } catch (err) {
        res.status(401).send('Unauthorized')
    }
})

Generally, in modern JavaScript, you should always be preferring promises to callbacks when possible - promises make chaining and catching asynchronous code much more convenient.

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!