我有这个功能,它是一个搜索查询。这工作正常,除非查询字符串名称不够详细,然后抛出错误消息
request( url, function (error, data) {
errorText = arguments['0'];
if (error) {
callback('Unable to connect to location services!', undefined)
} else if (errorText.includes('Cannot read property')) {
callback ('Unable to find location, try another search.', undefined)
}
else {
callback( {
data = data.body,
namePlace: data.suggestions[1].entities[0].name,
idPlace: data.suggestions[1].entities[0].destinationId,
})
}
})
来自控制台的错误信息是
namePlace: data.suggestions[1].entities[0].name,
^
TypeError: Cannot read property 'name' of undefined
我希望能够捕获此错误消息并回调“无法找到位置,请尝试其他搜索。”
答案 0 :(得分:1)
听起来您要检查的是 data.suggestions[1].entities
是否有任何条目。也许是这样的:
else if (data.suggestions[1].entities.length === 0) {
callback('Unable to find location, try another search.', undefined)
}
根据生成的数据结构的可靠性,您还可以检查 null
或 undefined
值。但是对于这个特定的错误,它看起来像是定义了 entities
并且是一个数组,但没有条目。
答案 1 :(得分:0)
需要改变第一个if
的逻辑顺序,否则else if (error)
会阻止if (errorText.includes('Cannot read property'))
。
您之前是否定义过 let request = new Request(<uri>)
?
你想做什么?
request( url, function (error, data) {
errorText = arguments['0']; // What are you trying to do here?
if (errorText.includes('Cannot read property')) {
callback ('Unable to find location, try another search.', undefined)
} else if (error) {
callback('Unable to connect to location services!', undefined)
} else {
callback( {
data = data.body, // What are you trying to do here?
namePlace: data.suggestions[1].entities[0].name, // What are you trying to do here?
idPlace: data.suggestions[1].entities[0].destinationId,
})
}
}); // <- semicolon here