I have a question about handling exceptions/errors. Consider this implementation using a try/catch. This is certainly one option, but I've also heard try/catch can be a little heavy-handed.
Option 1:
async function updateCustomerRegion(params, auth) {
const { id, region } = params;
const Customer = await CustomerModel();
const filter = { _id: id };
const update = { region: region };
try {
const customer = await Customer.findOneAndUpdate(filter, update, { new: true })
.lean()
.exec();
} catch (error) {
console.log(error);
throw "Error: Unable to update customer";
}
return {
count: customer ? 1 : 0,
data: customer
};
}
Another option is this implementation where I just throw an error if "customer" is false:
Option 2:
async function updateCustomerRegion(params, auth) {
const { id, region } = params;
const Customer = await CustomerModel();
const filter = { _id: id };
const update = { region: region };
const customer = await Customer.findOneAndUpdate(filter, update, { new: true })
.lean()
.exec();
if (!customer) throw "Error: Unable to update customer";
return {
count: customer ? 1 : 0,
data: customer
};
};
My question is, how functionally equivalent are these two implementations? Will Option #1 handle more than Option #2, or is using try/catch a little heavy-handed in this instance?
findOneAndUpdatedoes throw an exception or not. What does its documentation say?erroras the first one does, and it doesn't work for functions that normally return falsy values.