问题描述
您可以在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!