【发布时间】:2019-03-03 19:51:51
【问题描述】:
我正在尝试捕获来自 API 的 json 中不存在某个键时的错误,在本例中为 imageLinks.thumbnail。
这是我到目前为止写的,但我仍然收到 TypeError: Cannot read property 'thumbnail' of undefined.
let cover;
if(results.imageLinks === undefined){
let cover = "http://actar.com/wp-content/uploads/2015/12/nocover.jpg";
} else {
let cover = results.imageLinks.thumbnail;
};
我们将不胜感激。
干杯
【问题讨论】:
-
这是非常少的调试信息,您介意添加什么是
results,它包含什么?我不明白为什么要在 3 个不同的地方使用let cover,因为每次你这样做时,如果你想使用相同的变量,它就会产生新的变量,只需定义一次并使用它。 -
您确定您在该行收到该错误吗?你在其他地方引用它吗?注意:这个问题与从 API 获取 JSON 无关。您正在处理 JavaScript 对象,而不是 JSON。
-
如果
results.imageLinks未定义,它将永远不会执行else块。
标签: javascript node.js json error-handling