如何捕获带有自定义错误信息的"TypeError: Cannot read properties of undefined (read ɰ')“?

问题描述

您可以在catch块中移动throw语句。

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

更新

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

let propToCheck = 'borders';

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

解决方法

如何捕获不存在的属性的错误?示例:

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

现在,当我试图访问一个可能存在也可能不存在的属性时,如果它不存在,那么如何抛出并捕获自定义消息的错误?

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

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

我知道,如果我像下面这样通过可选的更改来检查属性的存在,那么我就可以用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);
}

在上面的代码行中,undefined是可捕获的,但不是实际的错误。但是如何用定制的错误消息捕获实际的错误'Cannot read properties of undefined (reading '0')'呢?

输出:Error: No neighbour found!

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...