Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

217
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda