Skip to content

Instantly share code, notes, and snippets.

@maxkramer
Last active December 29, 2015 05:09
Show Gist options
  • Save maxkramer/7619326 to your computer and use it in GitHub Desktop.
Save maxkramer/7619326 to your computer and use it in GitHub Desktop.
All screenshots and no gists makes James unhappy.
var renderError = function(res, error) {
res.status = 404;
res.render('error', {
title: 'Error',
error: error
});
};
exports.findWithId = function(req, res) {
var Article = mongoose.model('Article');
Article.findById(req.params['id'], function(err, article) {
console.log(err + " " + article);
if (err) {
renderError(res, err.message);
}
else {
if (article == undefined || article == null) {
renderError(res, "No article with id " + req.params["id"] + " exists.");
}
else {
renderSuccess(res, article);
}
}
});
};
@sandfox
Copy link

sandfox commented Nov 23, 2013

Arrggh, had a huge comment but fucking Preview button did something weird and deleted my comments

in short, you should specify some error handler function as mentioned here :: http://expressjs.com/guide.html#error-handling

and then in your function just call next(err) with some error message

exports.findWithId = function(req, res, next) {
    var Article = mongoose.model('Article');
    Article.findById(req.params['id'], function(err, article) {
        if (err) {
            return next(err);
        }
        if (article == undefined || article == null) {
            return next(new Error("No article with id " + req.params["id"] + " exists."));
        }
        renderSuccess(res, article);
    });
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment