Javascript: Try-catch Overlapping

Asked 1 years ago, Updated 1 years ago, 67 views

Hello.

The three queries below are conditions, so I want to write a prerequisite first and write a condition statement, but if one of those queries is undefined, the code stops due to an error.

const getEmptyCartQuery = await shopping_cart.findOne({
  (...)
});
const needsUpdatedQuantityQuery = await shopping_cart.findOne({
  (...)
});
const needsNewCartQuery = await shopping_cart.findOne({ 
  (...)
});

So I made an exception with the try-catch statement and made the code as below.

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 goes back anyway, but do you use such overlapping try-catch statements? It looks so messy, but is there any way for the code to flow without an error during the db inquiry other than try-catch

If there is something that needs to be supplemented because there is something lacking in the questions I posted, please leave a comment.

Thank you.

javascript node.js koa try-catch

2022-09-21 22:51

1 Answers

I searched for sort find or fail, but I see a response like . Since it's Promise anyway, I'm telling you to hang .then() but I don't know what it's be like. What does the error say?


2022-09-21 22:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.