Skip to content

Commit

Permalink
Merge pull request #14390 from Automattic/vkarpov15/gh-14377
Browse files Browse the repository at this point in the history
fix(connection): avoid unhandled error on createConnection() if on('error') handler registered
  • Loading branch information
vkarpov15 committed Mar 1, 2024
2 parents 8719def + e6f6d44 commit ec6a999
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
24 changes: 24 additions & 0 deletions lib/connection.js
Expand Up @@ -829,6 +829,30 @@ Connection.prototype.openUri = async function openUri(uri, options) {
return this;
};

/*!
* Treat `on('error')` handlers as handling the initialConnection promise
* to avoid uncaught exceptions when using `on('error')`. See gh-14377.
*/

Connection.prototype.on = function on(event, callback) {
if (event === 'error' && this.$initialConnection) {
this.$initialConnection.catch(() => {});
}
return EventEmitter.prototype.on.call(this, event, callback);
};

/*!
* Treat `once('error')` handlers as handling the initialConnection promise
* to avoid uncaught exceptions when using `on('error')`. See gh-14377.
*/

Connection.prototype.once = function on(event, callback) {
if (event === 'error' && this.$initialConnection) {
this.$initialConnection.catch(() => {});
}
return EventEmitter.prototype.once.call(this, event, callback);
};

/*!
* ignore
*/
Expand Down
15 changes: 15 additions & 0 deletions test/connection.test.js
Expand Up @@ -916,6 +916,21 @@ describe('connections:', function() {
assert.equal(err.name, 'MongooseServerSelectionError');
});

it('avoids unhandled error on createConnection() if error handler registered (gh-14377)', async function() {
const opts = {
serverSelectionTimeoutMS: 100
};
const uri = 'mongodb://baddomain:27017/test';

const conn = mongoose.createConnection(uri, opts);
await new Promise(resolve => {
conn.on('error', err => {
assert.equal(err.name, 'MongoServerSelectionError');
resolve();
});
});
});

it('`watch()` on a whole collection (gh-8425)', async function() {
this.timeout(10000);
if (!process.env.REPLICA_SET) {
Expand Down

0 comments on commit ec6a999

Please sign in to comment.