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

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

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