I have an error-handling middlware in Express that tries to catch all incoming errors:
app.use(function(err, req, res, next){
console.error(err.stack);
res.status(500);
res.render('500.jade');
});
But for some reason whenever I close mongod
process, my application crashes with the following stack trace:
Error: failed to connect to [localhost:27017]
at null.<anonymous> (/<hidden>/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:540:74)
at EventEmitter.emit (events.js:106:17)
at null.<anonymous> (/<hidden>/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:140:15)
at EventEmitter.emit (events.js:98:17)
at Socket.<anonymous> (/<hidden>/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js:478:10)
at Socket.EventEmitter.emit (events.js:95:17)
at net.js:441:14
at process._tickCallback (node.js:415:13)
Process finished with exit code 8
I have tried using the following configuration, but it didn't help me:
var options = {
server:{
auto_reconnect: true,
poolSize: 10,
socketOptions:{
keepAlive: 1
}
},
db: {
numberOfRetries: 10,
retryMiliSeconds: 1000
}
}
mongoose.connect(config.db, options);
One might wonder "why would you want your application to be running if it's essentially no longer functioning without a database connection?". I don't want it to crash and restart itself. Supervisor and Forever modules seem to stop trying to reconnect after a certain number of tries, thus leaving your application hanging in a crashed state.
Ideally, when MongoDB crashes I would like to display a 500.jade error page to users, meanwhile server should keep trying to reconnect to the database every 10 seconds. Once reconnected, resume all normal operations.
EDIT: None of the solutions posted below have worked for me, with the exception of domains.