I am trying to create a conditional statement first because there are three conditions below, and if one of those queries is undefined, the code stops because of an error.
const getEmptyCartQuery = await shopping_cart.findOne({
(...)
});
const needsUpdatedQuantityQuery = await shopping_cart.findOne({
(...)
});
const needsNewCartQuery = await shopping_cart.findOne({
(...)
});
So I wrote the following code with exception handling with a try-catch statement.
const data = await shopping_cart.findAll({
where: { cart_id }
});
try {
const getEmptyCart = await shopping_cart.findOne({ (...) });
if (getEmptyCart) {
await shopping_cart.update({ (...) });
}
ctx.body = data;
} catch (e) {
try {
const needsUpdatedQuantity = await shopping_cart.findOne({ (...) });
if (needsUpdatedQuantity) {
await shopping_cart.update({ (...) });
}
ctx.body = data;
} catch (e) {
try {
const needsNewCart = await shopping_cart.findOne({ (...) });
if (needsNewCart) {
await shopping_cart.create({ (...) });
}
} catch (e) {
ctx.status = 400;
ctx.body = e.message;
}
}
}
It works, but can I use a nested try-catch statement like above? Is there any other way that the code can flow without errors during db lookup instead of try-catch?
Please let me know by comment or reply if you have any additional information I need to supplement.
Thank you.