Express Error Handling Middleware Best Practice

Viewed 300

I have a web app written in Node.js and Express. Currently, I am trying to handle errors from the middlewares I am using. I have the following code:

app.get('/middleware1', (req, res, next) => {
  function1().then(() => {
    res.send("success");
  }).catch((err) => {
    next(new Error("there is error at 1");
  })
})

app.get('/middleware2', (req, res, next) => {
  // some codes here
  if (err) {
    next(new Error("there is error at 2");
  }
})

app.use(function(err, req, res, next) {
  console.error(err);
  next(err);
})

The first is using .catch and the second is simply a if statement. Could I catch both errors with the Express error handling middleware? I am quite new to Express, what would be the best practices of handling errors in Express and using the error handling middleware?

0 Answers
Related