how to handle disconnect error for MongoDB

Viewed 1073

I am seeing this uncaught exception in my Node.js process:

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

I tried capturing/trapping it using:

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

but that does not seem to be able to trap the error. Anyone know how I can do so?

4 Answers

There are 2 distinct types of connection errors when using the MongoDB driver:

  1. Errors during initial connection
  2. Errors after initial connection is established

The 'error' event is used to handle (2). It looks like you're looking for the correct way to handle initial connection errors. For those, you should either pass a callback to connect() or .catch() on the promise that connect() returns.

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

Use monk for the problem. I had faced the same problem a year ago but the monk saved me.

Here is a Example

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

I hope this will fix you problem. Have a good day!

The client doesn't emit events. The DB does. Get access to the db with client.db(dbName)

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

Well you can try it out with d.connect:

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