如何处理MongoDB断开连接错误

nr7wwzry  于 2022-11-03  发布在  Go
关注(0)|答案(4)|浏览(422)

我在我的Node.js进程中看到了这个未捕获的异常:

Uncaught exception: { Error: read ETIMEDOUT
    at TCP.onStreamRead (internal/stream_base_commons.js:162:27)
  name: 'MongoNetworkError',
  errorLabels: [ 'TransientTransactionError' ],
  [Symbol(mongoErrorContextSymbol)]: { isGetMore: true } }

我尝试使用以下工具捕获/陷印它:

import * as mdb from 'mongodb'
const d = new mdb.MongoClient(...);
d.on('error', () => {...});  // trap it here

但这似乎并不能捕获错误。有人知道我怎么做吗?

ndh0cuux

ndh0cuux1#

在使用MongoDB驱动程序时,有两种不同类型的连接错误:
1.初始连接期间出错
1.建立初始连接后出现错误
“error”事件用于处理(2)。看起来您正在寻找正确的方法来处理初始连接错误。对于这些错误,您应该传递一个回调到connect()connect()返回的承诺.catch()

const NUM_RETRIES = 3;
const delay = 1000;
let error = null;
for (let i = 0; i < NUM_RETRIES; ++i) {
  if (i > 0) {
    await new Promise(resolve => setTimeout(resolve, i * delay));
  }
  try {
    await mdb.MongoClient.connect(uri);
    break;
  } catch (err) {
    error = err;
  }
}
l5tcr1uw

l5tcr1uw2#

客户端不发出事件。数据库发出事件。使用client.db(dbName)获取access to the db

import * as mdb from 'mongodb'
const d = new mdb.MongoClient(url, options, function (err, client) {
  if (err) //do something
  const d = client.db(dbName);
  // available events: close,error,fullsetup,parseError,reconnect,timeout
  d.on('timeout', () => {...});  // trap it here
});
sd2nnvve

sd2nnvve3#

您可以尝试使用d.connect:

import * as mdb from 'mongodb'
const d = new mdb.MongoClient(...);
d.connect("your url").then().catch(err => {
      console.log(err)
})
v6ylcynt

v6ylcynt4#

monk来解决这个问题。一年前我也遇到过同样的问题,但是monk救了我。
以下是一个示例

const monk = require('monk')
const db = monk()

db.on('timeout', () => {
  console.log('Mongo connection lost')
})

db.on('close', () => {
  console.log('Mongo connection closed')
})

db.on('reconnect', () => {
  console.log('Mongo reconnected')
})

db._db.on('timeout', () => {
  console.log('Mongo connection lost')
})

db._db.on('close', () => {
  console.log('Mongo connection closed')
})

db._db.on('reconnect', () => {
  console.log('Mongo reconnected')
})

相关问题