【问题标题】:How to Catch "TypeError: Cannot read properties of undefined (reading '0')" with custom error message?如何使用自定义错误消息捕获“TypeError:无法读取未定义的属性(读取'0')”?
【发布时间】:2021-12-09 00:22:05
【问题描述】:

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

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!

【问题讨论】:

    标签: javascript debugging error-handling javascript-debugger


    【解决方案1】:

    您可以将 throw 语句移动到 catch 块内。

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

    【讨论】:

    • 如果出现多个错误怎么办?我期待 API 返回并使用他们自己的自定义错误消息检查多个属性?所以至少要知道日志的错误?谢谢
    • 在这种情况下,您可以检查该属性是否存在于对象上。在您的示例中,您想检查您的 arr[0] 对象上是否存在borders 属性并抛出您的自定义消息。请参阅我的答案中的更新代码。
    猜你喜欢
    • 2023-02-26
    • 2016-11-17
    • 2023-01-14
    • 1970-01-01
    • 2020-05-16
    • 1970-01-01
    • 2014-04-14
    • 2022-07-06
    • 2022-12-24
    相关资源
    最近更新 更多