Skip to content

Commit a917dfa

Browse files
authoredJun 24, 2021
fix(NODE-2035): Exceptions thrown from awaited cursor forEach do not propagate (#2852)
1 parent b98f206 commit a917dfa

File tree

2 files changed

+76
-2
lines changed

2 files changed

+76
-2
lines changed
 

‎lib/cursor.js

+12-2
Original file line numberDiff line numberDiff line change
@@ -742,7 +742,12 @@ class Cursor extends CoreCursor {
742742
return false;
743743
}
744744
if (doc != null) {
745-
iterator(doc);
745+
try {
746+
iterator(doc);
747+
} catch (error) {
748+
callback(error);
749+
return false;
750+
}
746751
return true;
747752
}
748753
if (doc == null && callback) {
@@ -762,7 +767,12 @@ class Cursor extends CoreCursor {
762767
fulfill(null);
763768
return false;
764769
} else {
765-
iterator(doc);
770+
try {
771+
iterator(doc);
772+
} catch (error) {
773+
reject(error);
774+
return false;
775+
}
766776
return true;
767777
}
768778
});

‎test/functional/cursor.test.js

+64
Original file line numberDiff line numberDiff line change
@@ -4372,6 +4372,70 @@ describe('Cursor', function() {
43724372
}
43734373
);
43744374

4375+
describe('Cursor forEach Error propagation', function() {
4376+
let configuration;
4377+
let client;
4378+
let cursor;
4379+
let collection;
4380+
4381+
beforeEach(function(done) {
4382+
configuration = this.configuration;
4383+
client = configuration.newClient({ w: 1 }, { maxPoolSize: 1 });
4384+
client
4385+
.connect()
4386+
.then(() => {
4387+
collection = client.db(configuration.db).collection('cursor_session_tests2');
4388+
done();
4389+
})
4390+
.catch(error => {
4391+
done(error);
4392+
});
4393+
});
4394+
4395+
afterEach(function(done) {
4396+
if (cursor) {
4397+
cursor
4398+
.close()
4399+
.then(() => client.close())
4400+
.then(() => done());
4401+
} else {
4402+
client.close().then(() => done());
4403+
}
4404+
});
4405+
4406+
// NODE-2035
4407+
it('should propagate error when exceptions are thrown from an awaited forEach call', function(done) {
4408+
const docs = [{ unique_key_2035: 1 }, { unique_key_2035: 2 }, { unique_key_2035: 3 }];
4409+
collection
4410+
.insertMany(docs)
4411+
.then(() => {
4412+
cursor = collection.find({
4413+
unique_key_2035: {
4414+
$exists: true
4415+
}
4416+
});
4417+
cursor
4418+
.forEach(() => {
4419+
throw new Error('FAILURE IN FOREACH CALL');
4420+
})
4421+
.then(
4422+
() => {
4423+
done(new Error('Error in forEach call not caught'));
4424+
},
4425+
err => {
4426+
try {
4427+
expect(err.message).to.deep.equal('FAILURE IN FOREACH CALL');
4428+
done();
4429+
} catch (error) {
4430+
done(error);
4431+
}
4432+
}
4433+
);
4434+
})
4435+
.catch(error => done(error));
4436+
});
4437+
});
4438+
43754439
it('should return a promise when no callback supplied to forEach method', function(done) {
43764440
const configuration = this.configuration;
43774441
const client = configuration.newClient({ w: 1 }, { poolSize: 1, auto_reconnect: false });

0 commit comments

Comments
 (0)
Please sign in to comment.