I can't seem to find similar codes handling errors properly in bulkwrite so I just want to ask if I am doing it right.
What I am trying to do is just have one single try/catch and when there are other promises, I would just check for instanceof Error
and throw that in the try/catch. Is this right or there is a better/cleaner way of doing this? Thanks a lot.
try {
// other logic here
const bulkWriteResult = await new Promise((resolve, reject) => {
try {
Student.collection.bulkWrite(
bulkUpdateOps,
{ ordered: true, w: 1 },
(err, result) => {
if (err) reject(err);
resolve(result);
},
);
} catch (err) {
reject(err);
}
});
if (bulkWriteResult instanceof Error) {
const error = new Error('Unable to batch update students');
error.code = 500;
throw error;
}
} catch (err) {
// handle all thrown error
}