简体   繁体   中英

Throwing errors in loop JS

I have some toggled feature values on backend and I need to compare them with some values on frontend side. This way website decides if it should show calendar, menu... (it's not the issue here).

From backend I get array for let say seven simple objects:

[
  {name: "menu1"; value: "password"}
  {name: "menu2"; value: "password"}
  ...
  {name: "menu7"; value: "password"}
]

On front end I have an object:

  {
    "menu1": true;
    "menu1": true;
    ...
    "menu6": true;
  }

I'm using axios to get this data. Problem I have is this: even if I have 6 values that are present on frontend, whole website will crash, because of this one feature that don't exist. It's working as intended, but I would like to throw correct error. Here's the code:

  loadAttributes(URL) {
    return axios.get(URL)
      .then(res => {
          const {attributes} = res.data;
          const toggles = {};
          for (let i = 0; i < attributes.length; i++) {
              if (Constants.featureToggleMDs[attributes[i].name] === undefined) {
                 throw (new Error(`There is a feature: ${attributes[i].name} in ACS that is not presented in constants.`));
              }
              const left = Constants.featureToggleMDs[attributes[i].name].toUpperCase();
              const right = sha512(attributes[i].value).toUpperCase();

              toggles[attributes[i].name] = (left === right);
            }
            return toggles;
        }).catch(e => console.error(`[Feature Toggle] Attributes not supported: ${e}`));
  }

I have an condition to check if value exists in frontend object, and when debugging, I only enter this part of the code once for "menu7". Unfortunately error is thrown 7 times. And that's the issue here. How and why it's thrown and caught 7 times? Is this an axios issue? I tried simplify it with snippet below and it's working correctly. But not in my project. Any ideas?

 let attributes = [ { name: 'menu1', value: 'one' }, { name: 'menu2', value: 'two' }, { name: 'menu3', value: 'one' }, { name: 'menu4', value: 'two' }, { name: 'menu5', value: 'one' } ]; defaultFeatureToggles = { 'menu1': false, 'menu2': false, 'menu3': false, 'menu4': false }; for (let i = 0; i < attributes.length; i++) { if(defaultFeatureToggles[attributes[i].name] === undefined) { console.warn(`This ${attributes[i].name} don't exists.`); } } 

The reason for my multiple throws was simple. I used this function in other place I forgot about it. Everything works fine now. Sorry for space wasting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM