Error Handling GET all resources

suggest change

How do you handle errors, rather than only logging them? Pass the error to Express with next(err). The route callback has to accept next, and next(err) belongs in the error branch, not the success branch.

Bad way:

Router.route('/')
  .get((req, res) => {
    Request.find((err, r) => {
      if(err){
        console.log(err)
      } else {
        res.json(r)
      }
    })
  })
  .post((req, res) => {
    const request = new Request({
      type: req.body.type,
      info: req.body.info
    });
    request.info.user = req.user._id;
    console.log("ABOUT TO SAVE REQUEST", request);
    request.save((err, r) => {
      if (err) {
        res.json({ message: 'there was an error saving your r' });
      } else {
        res.json(r);
      }
    });
  });

Better way:

Router.route('/')
  .get((req, res, next) => {
    Request.find((err, r) => {
      if (err) return next(err);
      res.json(r);
    });
  })
  .post((req, res, next) => {
    const request = new Request({
      type: req.body.type,
      info: req.body.info
    });
    request.info.user = req.user._id;
    request.save((err, r) => {
      if (err) return next(err);
      res.json(r);
    });
  });

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents