lundi 28 mars 2016

What is the best practice for custom error handling method in node/express

I am trying to make a common method to take care of errors after getting document from db. The original code is

Folder.findById(req.params.id, function (err, folder) {
  if (err) {
    next(err);
  } else if (!folder) {
    res.send(404, null);
  } else if (!folder.isActive()) {
    res.send(410, null);
  } else if (folder.user.toString() !== req.session.user.toString()) {
    res.send(403, null);
  } else {
    req.retrievedFolder = folder;
    next();
  }
});

Then, I separated the error handling part to be able to use it in other places.

Folder.findById(req.params.id, function (err, folder) {
  if (handleError(err, folder, req, res)) {
    req.retrievedFolder = folder;
    next();
  }
});

(in another file)

function handleError(err, doc, req, res) {
   if (err) {
     next(err);
   } else if (!doc) {
     res.send(404, null);
   } else if (!doc.isActive()) {
     res.send(410, null);
   } else if (doc.user.toString() !== req.session.user.toString()) {
     res.send(403, null);
   } else {
     return true;
   }
   return false;
}

But sending response and returning boolean in one method feels it is violating separation of concerns. What is the best practice for a helper function to handle errors in if statement in node/express?

Aucun commentaire:

Enregistrer un commentaire