使用connect-mongo时处理数据库错误

我有一个相当标准的连接mongo设置

在此之前,mongoose被初始化/连接

app.use(express.session({ secret: "sfdgsdgsdfg", store: new MongoSessionStore({db: mongoose.connection.db}) })); 

这工作正常。

但是 – 假设我的mongodb连接突然死掉(在下面的例子中本地停止mongod) – 下一次我尝试点击一个路由时,我的快速应用崩溃了 –

错误:无法连接到[localhost:27017]。 (/Users/alex/Projects/MyProject/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:540:74)at emit(events.js:106:17)at null。 (/Users/alex/Projects/MyProject/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:140:15)在发射(events.js:98:17)在Socket。 (/Users/alex/Projects/MyProject/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js:478:10)在Socket.mit(events.js:95:17)在net.js: 440:14在process._tickCallback(node.js:419:13)

有没有办法来处理这个错误,(例如)redirect到/错误路线? (很显然,不需要会话!)

编辑

所以现在,我正在创build一个单独的mongoose连接。

然后我使用on('error'来听错误

…这是我卡住的地方 – 进程仍然死亡,因为重新抛出的错误不会传递到明确的error handling程序…

 var sessionDbConnection = mongoose.createConnection(config.sessionDb); sessionDbConnection.on('error', function(err) { console.log('oops'); throw err; //instead of re-throwing the error, i think i need to pass it to the error handler below?? }) app.use(express.session({ secret: "sfdgsdgsdfg", store: new MongoSessionStore({db: sessionDbConnection.db}) })); app.use(function(err, req, res, next) { res.render('error', err); //just for testing }); 

在使用链的末尾设置一个通用error handling程序…

 //function must accept 4 arguments app.use(function(err, req, res, next) { //use accepts to determin if you should return json, html, image? //render the appropriate output. }); 

另外,如果发生错误,请让处理程序和其他模块接受三个参数(req, res, next) ,然后return next(err)通常您可以select使用.code属性来匹配您的http响应代码一个匹配的错误。 input错误使用4xx ,服务器错误使用5xx

另外,如果你想处理一般情况…

 process.on('uncaughtException', function(err) { console.error('Caught exception: ' + err); console.error(err.stack); //interrogate the error, if it's something you can recover from, let it be. //if the exception is fatal, exit with prejudice setTimeout(process.exit.bind(process, 666), 1000); //exit in a second }); 

这将处理你的具体情况,但是你应该只允许这个过程继续运行,如果它的东西应该自己恢复的话。


为了响应你的编辑…你可以有一个全局variables,当你得到一个数据库错误时会发生变化…不幸的是,这个错误不一定发生在http请求的上下文中。它可能发生在/之前/之后…就这样,你无法知道。

如果您使用的客户端将在失败时重新连接,那么这将缓解一些问题。 最好的办法是跟踪这个variables,为所有请求提供错误,然后重新启动你的进程。

pm2forever有很多模块可以帮助你。