我正在尝试捕获mongodb
断开连接事件。
使用以下设置可以正常工作:
simple.js
'use strict';
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/pnsockets', function () {
console.log('mongoose connected');
});
mongoose.connection.on('disconnected', function () {
console.log('mongoose disconnected');
});
如果simple.js
正在运行且我停止mongodb
(launchctl stop homebrew.mxcl.mongodb
),我会在控制台上获得mongoose disconnected
,我可以处理此问题。
但正在运行extended.js
usung socket.io-adapter-mongo
,当我杀死mongodb
时,我收到以下错误:
/project/node_modules/mongoose/node_modules/mongodb/lib/utils.js:98
process.nextTick(function() { throw err; });
^
MongoError: server localhost:27017 timed out
at null.<anonymous> (/project/node_modules/mongodb-core/lib/topologies/server.js:436:40)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at null.<anonymous> (/project/node_modules/mongodb-core/lib/connection/pool.js:144:10)
at g (events.js:260:16)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at Socket.<anonymous> (/project/node_modules/mongodb-core/lib/connection/connection.js:172:12)
at Socket.g (events.js:260:16)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at TCP._onclose (net.js:468:12)
extended.js
'use strict';
var mongoose = require('mongoose');
var socketIO = require('socket.io');
var MongoAdapter = require('socket.io-adapter-mongo');
mongoose.connect('mongodb://localhost:27017/pnsockets', function () {
console.log('mongoose connected');
_setupSocketAdapter();
});
mongoose.connection.on('disconnected', function () {
console.log('mongoose disconnected');
});
var _setupSocketAdapter = function () {
var io = socketIO();
var socket = mongoose.connections[0].db;
socket.connection = mongoose.connections[0]; // mubsub will need this line
var mongoAdapter = MongoAdapter({socket: socket});
io.adapter(mongoAdapter);
};
如何捕获MongoError: server localhost:27017 timed out
错误?
答案 0 :(得分:1)
问题来自socket.io-adapter-mongo本身。
如果您查看source code,他们会使用mubsub。 Mubsub基本上是Node.js和MongoDB的pub / sub实现。
他们正在设置一个客户端和一个通道,该通道使用上限集合进行一对一映射,但这些部件上没有附加事件处理程序。
根据mubsub documentation,频道上可以使用以下活动:*
,message
,document
,ready
和error
。 error
事件也可在客户端上获得。
例如,只需添加以下代码即可捕获您遇到的错误。
channel.on('error', function (err) {
console.error(err.message);
});
client.on('error', function (err) {
console.error(err.message);
});
如果断开连接,您将获得以下输出而不是未处理的错误。
mongoose connected
server localhost:27017 timed out
mongoose disconnected
Mubsub: broken cursor.