1

I'm building a small web application using Node.js, Express, Mongoose, and Passport. Everything is working, but I'm trying to make the application fail gracefully if the MongoDB user database is not available. The application makes a database call every time it deserializes the user out of the session, so I can't do much if the database is down. I just want to display a general error page to the user and recover if/when the database is back up.

Right now, in my local implementation, if I take down the MongoDB server (by just hitting CTRL-C) and then try to, say, reload a page with authentication, sometimes I get my global error page but mostly the application just hangs without generating any errors or console logs (despite the addition of multiple console.log() statements at key failure points, see below) and continues to hang on all future requests. If I then restart the MongoDB server, the application doesn't recover.

The complete source code is here but select code snippets are below.

Mongoose connection:

mongoose.connect(mongodbURI, mongodbConnectOptions);
// Log database events to the console for debugging purposes
mongoose.connection.on('open', function () {  
  console.log("Mongoose open event"); 
});
mongoose.connection.on('close', function () {  
  console.log("Mongoose close event"); 
});
mongoose.connection.on('connected', function () {  
  console.log("Mongoose connected event");
}); 
mongoose.connection.on('disconnected', function () {  
  console.log("Mongoose disconnected event"); 
});
mongoose.connection.on('error',function (err) {  
  console.log("Mongoose error event:");
  console.log(err)
}); 

The Passport deserializeUser() call:

passport.deserializeUser(function(id, done) {
    console.log("Attempting to deserialize user")
    User.findById(id, function(err, user) {
        if (err) console.log("Database error inside deserializeUser()");
        done(err, user);
    });
});

The global error handler (installed at the end of the Express stack):

var errorHandler = function(err, req, res, next) {
    console.log("Error caught by Express error handler")
    console.log(err);
    res.status(500);
    res.render('error', { error: err });
}
app.use(errorHandler);

I think this is probably related to this question, but I'm specifically trying to handle the case when the connection is completely lost (because the database is down). Suggestions?

tcquinn
  • 381
  • 1
  • 4
  • 15

0 Answers0