gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:00:24 27 4
gpt4 key购买 nike

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

Mongoose 在此之前已初始化/连接

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

这很好用。

但是-假设我的 mongodb 连接突然中断(在下面的示例中本地停止 mongod) - 下次我尝试选择路线时,我的 Express 应用程序也会崩溃 -

Error: failed to connect to [localhost:27017] at null. (/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) at emit (events.js:98:17) at Socket. (/Users/alex/Projects/MyProject/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/connection.js:478:10) at Socket.emit (events.js:95:17) at net.js:440:14 at process._tickCallback (node.js:419:13)

有没有办法处理这个错误并(例如)重定向到/error 路由?(显然不需要 session !)

编辑

现在,我正在创建一个单独的 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
});

最佳答案

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

//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),以防出现错误,返回 next(err) 通常,您需要选择使用 .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 有很多模块可以帮助您解决此问题。

关于node.js - 使用 connect-mongo 时处理数据库错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27139289/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com