【发布时间】: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