首页 文章

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

提问于
浏览
1

我有一个相当标准的connect-mongo设置

在此之前初始化/连接mongoose

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

这很好用 .

但是 - 假设我的mongodb连接突然死亡(在下面的例子中本地停止mongod) - 下次我尝试点击路线时,我的快递应用程序也崩溃了 -

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

有没有办法处理此错误和(例如)重定向到/错误路由? (显然是一个不需要会话!)

EDIT

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

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

...这就是我遇到的问题 - 进程仍然死亡,因为重新抛出错误并没有将它传递给快速错误处理程序......

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
});

1 回答

  • 1

    在使用链的末尾设置一般错误处理程序...

    //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) ,通常您可以选择使用 .code 属性将您的http响应代码与匹配错误的代码进行匹配 . 使用 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
    });
    

    这将处理您的具体情况,但您应该只允许该进程继续运行,如果它的'应该自己恢复的东西 .


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

    如果您正在使用将在失败时重新连接的客户端,那么这将缓解一些问题 . 您可以做的最好的事情是跟踪此变量,为所有请求提供错误..然后重新启动您的流程 .

    pm2forever 有很多模块可以帮助你解决这个问题 .

相关问题