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

109
Vistas
How can I handle runtime errors on Express app?

I'm new to express + node.js, so I'm written an rest api using mongoose. What's the best way to handle runtime errors as database errors etc.?

I've read in the express documentation that you can have a middleware function(err, res, req, next) to handle this errors, and you can call this function only calling next(err). That's ok, so Imagine you have a User moongose model and in a controller you write this function:

const find = (email, password) => {
  User.find({ email: email }, (err, doc) => {
    if (err) {
      // handle error
    }
    return doc;
  });
};

Then, you have in another file a handler for a route:

router.get('/users', (req, res) => {
    userController.find(req.body.email);
});

So, at this point, you can handle the mongo error writing throw(err) in the model and using try/catch in the controller to then call next(err) right? But I've read that using try/catch in JavaScript is not a good practice because it creates a new execution context etc.

What's the best way to handle this errors in Express?

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

I will suggest you to use promises. It not only makes your code cleaner but also error handling is much easier. For reference you can visit this or this.

If you are using mongoose you can plugin your own library of promise.

const mongoose = require('mongoose');
mongoose.connect(uri);

// plug in the promise library:
mongoose.Promise = global.Promise;

mongoose.connection.on('error', (err) => {
  console.error(`Mongoose connection error: ${err}`)
  process.exit(1)
})

And use it like below:

In controller:

const find = (email) => {
  var userQuery = User.find({ email: email });
  return userQuery.exec();
};

In Router:

router.get('/users', (req, res) => {
    userController.find(req.body.email).then(function(docs){
      // Send your response
    }).then(null, function(err){
      //Handle Error
    });
});
about 4 years ago · Santiago Trujillo 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