Saras Arya
Saras Arya

Reputation: 3112

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

I have a NodeJS Application with Express as my web server and Mongoose as my abstraction layer over MongoDB.Now a simple Express route is written like 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 I have at least 100 function like these in my app and instead of writing res.sendStatus(500) every time, I want to create one function like this.

var sendError = function(err, res, next) {
    if (err) {
        res.status(500).send(JSON.stringify({
            'message': "Internal server error. Couldn't connect to database. Please report this issue and try again"
        }));
        next();
    }
};

And for every DB call. if(err) sendError(err, res, next); Doesn't work and somehow I feel it's not right. So what is the best practice in this case?

Upvotes: 1

Views: 2599

Answers (1)

You can use Express.errorHandler for this purpose. It described in Express documentation.

Upvotes: 1

Related Questions