Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

219
Views
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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.');
}

Update

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

let propToCheck = 'borders';

if (!arr[0].hasOwnProperty(propToCheck)) {
  throw new Error(`${propToCheck} not found`);
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!