3

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

1 Answer 1

2

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`);
};
Sign up to request clarification or add additional context in comments.

2 Comments

What a stupid mistake, thank you very much! You have no idea how much time I spent trying to solve this.
My pleasure. Yup. It happens with everyone. :D

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.