Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

218
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda