如何使用自定义错误消息捕获"TypeError: Cannot read properties of undefined (reading '0')"?



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

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!

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

相关内容

  • 没有找到相关文章

最新更新