Skip to content

Commit e6f6d44

Browse files
committed
fix(connection): avoid unhandled error on createConnection() if on('error') handler registered
Fix #14377
1 parent c02141b commit e6f6d44

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

lib/connection.js

+24
Original file line numberDiff line numberDiff line change
@@ -829,6 +829,30 @@ Connection.prototype.openUri = async function openUri(uri, options) {
829829
return this;
830830
};
831831

832+
/*!
833+
* Treat `on('error')` handlers as handling the initialConnection promise
834+
* to avoid uncaught exceptions when using `on('error')`. See gh-14377.
835+
*/
836+
837+
Connection.prototype.on = function on(event, callback) {
838+
if (event === 'error' && this.$initialConnection) {
839+
this.$initialConnection.catch(() => {});
840+
}
841+
return EventEmitter.prototype.on.call(this, event, callback);
842+
};
843+
844+
/*!
845+
* Treat `once('error')` handlers as handling the initialConnection promise
846+
* to avoid uncaught exceptions when using `on('error')`. See gh-14377.
847+
*/
848+
849+
Connection.prototype.once = function on(event, callback) {
850+
if (event === 'error' && this.$initialConnection) {
851+
this.$initialConnection.catch(() => {});
852+
}
853+
return EventEmitter.prototype.once.call(this, event, callback);
854+
};
855+
832856
/*!
833857
* ignore
834858
*/

test/connection.test.js

+15
Original file line numberDiff line numberDiff line change
@@ -916,6 +916,21 @@ describe('connections:', function() {
916916
assert.equal(err.name, 'MongooseServerSelectionError');
917917
});
918918

919+
it('avoids unhandled error on createConnection() if error handler registered (gh-14377)', async function() {
920+
const opts = {
921+
serverSelectionTimeoutMS: 100
922+
};
923+
const uri = 'mongodb://baddomain:27017/test';
924+
925+
const conn = mongoose.createConnection(uri, opts);
926+
await new Promise(resolve => {
927+
conn.on('error', err => {
928+
assert.equal(err.name, 'MongoServerSelectionError');
929+
resolve();
930+
});
931+
});
932+
});
933+
919934
it('`watch()` on a whole collection (gh-8425)', async function() {
920935
this.timeout(10000);
921936
if (!process.env.REPLICA_SET) {

0 commit comments

Comments
 (0)