![](/img/trans.png)
[英]ReactJS - Javascript try/catch shows an error in the console
[英]Javascript catch error within console and callback message
我有这个功能,它是一个搜索查询。 这工作正常,除非查询字符串名称不够详细,然后抛出错误消息
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
我希望能够捕获此错误消息并回调“无法找到位置,请尝试其他搜索”。
听起来您要检查的是data.suggestions[1].entities
是否有任何条目。 也许是这样的:
else if (data.suggestions[1].entities.length === 0) {
callback('Unable to find location, try another search.', undefined)
}
根据结果数据结构的可靠性,您还可以检查null
或undefined
值。 但是对于这个特定的错误,它看起来像定义了entities
和一个数组,但没有条目。
您需要更改第一个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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.