node.js - How to do error handling in Express and NodeJS for Mongoose Error. -


i have nodejs application express web server , mongoose abstraction layer on mongodb.now simple express route written this.

module.exports.getprofile = function(req, res, next) {     users.findone({         '_id': req.user._id     }).exec(function(err, profile) {         if (err) {             res.sendstatus(500);         } else if (profile) {             res.status(200).send(json.stringify({                 'profile': profile             }));         } else {             res.status(400).send(json.stringify({                 'message': "profile not found"             }));         }     }); }; 

now have @ least 100 function these in app , instead of writing res.sendstatus(500) every time, want create 1 function this.

var senderror = function(err, res, next) {     if (err) {         res.status(500).send(json.stringify({             'message': "internal server error. couldn't connect database. please report issue , try again"         }));         next();     } }; 

and every db call. if(err) senderror(err, res, next); doesn't work , somehow feel it's not right. best practice in case?

you can use express.errorhandler purpose. described in express documentation.


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -