我获取数据并想输出数据。它有效,但我也想进行错误处理。
喜欢:
const func = async data => {
try {
const res = await fetch('MY_URL);
const out = await res.json();
if(out) {
const name = out.result.name;
if(out.result.error) {
console.log('ERROR');
}
}
} catch(e) {
console.log(e);
}
};
为什么我会收到这条消息?
Cannot read property 'error' of undefined
好吧,我没有一个有错误的对象,但我想说如果有一个错误对象,那么我想显示其他任何东西。
我该如何解决?
编辑:
// Error Handling Statuscode
if (out.result[0].statuscode.error) {
allCircle[0].innerHTML = errorIcon;
domainInfo[0].innerText = out.result[0].statuscode.error;
}
我没有状态码。错误。但是如果我的系统发生错误,那么我会收到属性错误。那么我怎么能说如果存在错误呢?因为错误属性并不总是存在。
答案 0 :(得分:0)
您可以尝试以下操作:
if(out.result && out.result.error) {
console.log('ERROR');
}
这样一来,如果最初没有 error
属性,您就可以快捷地评估 result
属性。
答案 1 :(得分:0)
为什么我会收到这条消息?
<块引用>无法读取未定义的属性“错误”
这是因为您的 out
对象没有每次都带有 result
参数,并且当时返回 undefined
所以您无法访问 out.result.error
因为 out.result
是 undefined
解决方案
if(out?.result?.error) {
console.log('ERROR');
}