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

167
Views
Problem with handling errors in Express framework

I am currently working on node.js + express + mongoDB project. I am trying to handle error that occurs when data cannot be received from database. I am simulating this by terminating mongod process in console and calling .get in Postman. Sadly instead of getting an error in Postman I only get Unhandled Promise Rejection in console. I read a lot of posts about error handling and implemented it according to this guide: https://expressjs.com/en/guide/error-handling.html. I would be grateful for any idea of how can I fix this.

The code:

Printing all courses:

router.get("/", async (req, res, next) => {
  try {
    const courses = await Course.find().sort("dishName");
    res.send(courses);
  } catch (ex) {
    next(ex);
  }
});

error.js:

module.exports = function (err, res, req, next) {
  res.status(500).send(`500 Error`);
};

index.js

const error = require(`./middleware/error`);

app.use(error);

app.use(error) is placed as the last app.use

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

There is a minor mistake in your code. The order of the req and res parameters in the error handler function should not be changed.

// Error.js
module.exports = function (err, req, res, next) {
  res.status(500).send(`500 Error`);
};
over 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!