Skip to content

Commit

Permalink
fix(NODE-2035): Exceptions thrown from awaited cursor forEach do not …
Browse files Browse the repository at this point in the history
…propagate (#2852)
  • Loading branch information
W-A-James committed Jun 24, 2021
1 parent b98f206 commit a917dfa
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 2 deletions.
14 changes: 12 additions & 2 deletions lib/cursor.js
Expand Up @@ -742,7 +742,12 @@ class Cursor extends CoreCursor {
return false;
}
if (doc != null) {
iterator(doc);
try {
iterator(doc);
} catch (error) {
callback(error);
return false;
}
return true;
}
if (doc == null && callback) {
Expand All @@ -762,7 +767,12 @@ class Cursor extends CoreCursor {
fulfill(null);
return false;
} else {
iterator(doc);
try {
iterator(doc);
} catch (error) {
reject(error);
return false;
}
return true;
}
});
Expand Down
64 changes: 64 additions & 0 deletions test/functional/cursor.test.js
Expand Up @@ -4372,6 +4372,70 @@ describe('Cursor', function() {
}
);

describe('Cursor forEach Error propagation', function() {
let configuration;
let client;
let cursor;
let collection;

beforeEach(function(done) {
configuration = this.configuration;
client = configuration.newClient({ w: 1 }, { maxPoolSize: 1 });
client
.connect()
.then(() => {
collection = client.db(configuration.db).collection('cursor_session_tests2');
done();
})
.catch(error => {
done(error);
});
});

afterEach(function(done) {
if (cursor) {
cursor
.close()
.then(() => client.close())
.then(() => done());
} else {
client.close().then(() => done());
}
});

// NODE-2035
it('should propagate error when exceptions are thrown from an awaited forEach call', function(done) {
const docs = [{ unique_key_2035: 1 }, { unique_key_2035: 2 }, { unique_key_2035: 3 }];
collection
.insertMany(docs)
.then(() => {
cursor = collection.find({
unique_key_2035: {
$exists: true
}
});
cursor
.forEach(() => {
throw new Error('FAILURE IN FOREACH CALL');
})
.then(
() => {
done(new Error('Error in forEach call not caught'));
},
err => {
try {
expect(err.message).to.deep.equal('FAILURE IN FOREACH CALL');
done();
} catch (error) {
done(error);
}
}
);
})
.catch(error => done(error));
});
});

it('should return a promise when no callback supplied to forEach method', function(done) {
const configuration = this.configuration;
const client = configuration.newClient({ w: 1 }, { poolSize: 1, auto_reconnect: false });
Expand Down

0 comments on commit a917dfa

Please sign in to comment.