简体   繁体   中英

How to Catch "TypeError: Cannot read properties of undefined (reading '0')" with custom error message?

How to catch the error for property that does not exist? Example:

const arr = [
  {
    neighbours: ['AFG', 'CNG'],
  },
];

Now when i try to access a property which may or may not exist, in case, it does not exist then how to throw and catch the error with custom message?

 try {
  const nearBorder = arr[0].borders[0];

  // Above statement returns Error: Cannot read properties of undefined (reading '0')"
  // Now how to throw above error with custom error message?

  if (!nearBorder) {
    throw new Error('No neighbour found!');
  } else {
    console.log(`Your border is ${nearBorder}`);
  }
} catch (err) {
  console.log(err);
}

Output: TypeError: Cannot read properties of undefined (reading '0')

I know, if i check the property existence via optional changing like below then i can throw the custom message with undefined :

try {
  const nearBorder = arr[0].borders?.[0]; // returns undefined, NOT the actual error

  if (!nearBorder) {
    throw new Error('No neighbour found!');
  } else {
    console.log(`Your border is ${nearBorder}`);
  }
} catch (err) {
  console.log(err);
}

In above line, the undefined is catch able but NOT the actual error. But how to catch the actual error 'Cannot read properties of undefined (reading '0')' with custom error message?

Output: Error: No neighbour found!

You can move your throw statement inside catch block.

 const arr = [{ neighbours: ['AFG', 'CNG'] }] try { let nearBorder = arr[0].borders[0]; if (nearBorder) { console.log(`Your border is ${nearBorder}`); } } catch (e) { throw new Error('No neighbour found.'); }

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