Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

110
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda