Skip to content

Instantly share code, notes, and snippets.

@bjrmatos
Created January 31, 2015 04:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjrmatos/1b47cc045333eed064e5 to your computer and use it in GitHub Desktop.
Save bjrmatos/1b47cc045333eed064e5 to your computer and use it in GitHub Desktop.
higher order error handling
/* Turn this */
router.get("/api/products/:id", function(req, res) {
Product.getProduct(req.params.id, function(err, products) {
if (err) {
res.status(404).json({"message": "Not Found"});
}
else {
res.status(200).json(products);
}
});
});
router.get("/api/users/:id", function(req, res) {
User.getUserById(req.params.id, function(err, user) {
if (err) {
res.status(404).json({"message": "Not Found"});
}
else {
User.updateUser(id, req.body, function(err, user) {
if (err) {
res.status(400).json({"message": "Invalid data provided"});
}
else {
res.status(200).json(user);
}
});
}
});
}
/* Into this */
function ensure(notOkCode, notOkMessage, response, okFx) {
return function(err) {
if (err) {
response.status(notOkCode).json({"message": notOkMessage});
}
else {
okFx.apply(okFx, Array.prototype.slice.call(arguments, 1));
}
};
}
var ensureFound = _.partial(ensure, 404, "Not Found"),
ensureValid = _.partial(ensure, 400, "Bad Request");
router.get("/api/products/:id", function(req, res) {
Product.getProduct(req.params.id, ensureFound(res, function(product) {
res.status(200).json(product);
}));
});
router.get("/api/users/:id", function(req, res) {
User.getUserById(req.params.id, ensureFound(res, function(user) {
User.updateUser(user, req.body, ensureValid(res, function(updated) {
res.status(200).json(updated);
}));
}));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment