Ryan Griggs
Ryan Griggs

Reputation: 2758

MongoDB/Mongoose unhandled error on disconnect - why isn't it firing on('error') event?

I'm connecting to a MongoDB database using the mongoose library.

After running mongoose.connect() I'm creating a mongoose.connection.on('error') handler.

After the app starts, I stop the MongoDB service to simulate a 'lost-connection event'. The script outputs:

events.js:196
    throw er; // Unhandled 'error' event
    ...

and my app crashes.

The on('error') handler never executes. Why not? Isn't that the point of this event handler: to handle errors that the MongoDB connection throws, to avoid the app crashing?

Expected behavior: if the MongoDB connection is lost, the app attempts to reconnect indefinitely.

What am I doing wrong?

Here's my full connection code:

function dbConnect() {
// Establish MongoDB connection
    logger.debug(`Connecting to MongoDB database ${process.env.DB_SERVER}:${process.env.DB_PORT} database ${process.env.DB_DATABASE}...`)

    // Set up connection string
    const db_uri = `mongodb://${process.env.DB_USER}:${process.env.DB_PASS}@${process.env.DB_SERVER}:${process.env.DB_PORT}/${process.env.DB_AUTH_DATABASE}`

    // Initiate connection:
    mongoose.connect(db_uri, { 
        dbName: process.env.DB_DATABASE,        // Connect to the specified database
        useNewUrlParser: true,                  // Use new settings
        useUnifiedTopology: true,
        useCreateIndex: true,
        autoIndex: process.env.DB_AUTO_INDEX,   // Autoindex
        reconnectTries: Number.MAX_VALUE,       // Keep retrying forever (thanks https://stackoverflow.com/a/39684734/1502289 and https://stackoverflow.com/a/41923785/1502289)
        reconnectInterval: 5000,                // Time to wait between reconnection attempts
    })
    .then(() => {
        logger.debug("MongoDB successful connection")
    })
    .catch((err) => {
        logger.debug("MongoDB connection error", err)
    })

    const db = mongoose.connection

    // Set up database event handlers:
    db.on('error', function(err) { logger.error("Unable to connect to database.  Error: " + err) } )

    db.once('open', function() { 
        logger.debug('Mongoose database connection established.')

        // Load common properties from database:

        // ... [snip]

    })

    db.on('disconnected', function() {
        logger.error('MongoDB disconnected.  Attempting to reconnect...')
    })

    db.on('reconnected', function() { logger.debug('Mongoose reconnected.')})
}

Upvotes: 1

Views: 1912

Answers (0)

Related Questions