Home > Blockchain >  How to handle errors with Async-Await for mongoose Express?
How to handle errors with Async-Await for mongoose Express?

Time:12-08

I am confused on the best practices for using Mongoose with express js with trying to render a page that contains data (with EJS).

I know of the two following methods:

Method 1: Using Async Await

app
  .route("/")
  .get(async (req, res) => {
    const items = await imgModel.find({});
    res.render("home", { items });
  })
  .post((req, res) => {
    res.render("home");
  });

Issue with Method 1: No callback function, so I cannot check for error from the call to the DB

Method 2: Callback function that allows me to check for erro

app
  .route("/")
  .get((req, res) => {
    imgModel.find({}, (err, items) => {
      if (err) {
        res.status(500).send("error", err);
      } else {
        res.render("home", { items });
      }
    });
  })
  .post((req, res) => {
    res.render("home");
  });

Problem with Method 2: No use of Async-Await

I used both methods and they work fine, but I did not have issues with the database so I did not need to handle errors, otherwise I might face issues with method 1 which I think is closer to the preffered practice

CodePudding user response:

async/await errors can be handled with a try/catch...

app
  .route("/")
  .get(async (req, res) => {
    try {
      const items = await imgModel.find({});
      res.render("home", { items });
    } catch (err) {
      res.status(500).send("error", err);
    }
  })
  .post((req, res) => {
    res.render("home");
  });

CodePudding user response:

While @danh response should solve this problem , i would argue using next

   app
      .route("/")
      .get( async (req, res, next) => {
        try {
          const items = await imgModel.find({});
           res.render("home", { items });
        } catch (err) {
           res.status(500)
           next(err)
        }
     })
    .post((req, res) => res.render("home"));

and then the last route you want to add a middleware to handle all errors that might occur

app.use((err,req,res,next) => {
 if(res.statusCode === 500)
  //do something 
  // for example render a page with a message
 if(res.statusCode === 404)
  // do something

}) 

considering i hate the the default EJS error with passion (when it fails to render a page) i would argue that you should do error control during page render

res.render("home", { items }, (err,html) =>{
  if(err){
   res.status(500)
   return next(err)
  }
  res.status(200).send(html)
} )

for more on errorHandling check Express docs

  • Related