开发者

How to handle errors with Async-Await for mongoose + Express?

开发者 https://www.devze.com 2022-12-07 20:01 出处:网络
I am confused on the best practices for usi开发者_C百科ng Mongoose with express js with trying to render a page that contains data (with EJS).

I am confused on the best practices for usi开发者_C百科ng 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


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");
  });
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号