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

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

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