Created
January 31, 2015 04:57
-
-
Save bjrmatos/1b47cc045333eed064e5 to your computer and use it in GitHub Desktop.
higher order error handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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