Reputation: 55
I have this function which is a search query. This works fine unless the query string name is not detailed enough which then throws up an error 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,
})
}
})
The error message from the console is
namePlace: data.suggestions[1].entities[0].name,
^
TypeError: Cannot read property 'name' of undefined
I want to be able to capture this error message and callback 'Unable to find location, try another search.'
Upvotes: 0
Views: 29
Reputation: 2705
You need to change the logical order of the first if
, otherwise else if (error)
will prevent if (errorText.includes('Cannot read property'))
.
Have you previously defined let request = new Request(<uri>)
?
What is it that you're trying to do?
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
Upvotes: 0
Reputation: 218837
It sounds like what you want to check for is whether data.suggestions[1].entities
has any entries. Perhaps something like:
else if (data.suggestions[1].entities.length === 0) {
callback('Unable to find location, try another search.', undefined)
}
Depending on how reliable the resulting data structure is, you might also check for null
or undefined
values. But for this particular error it looks like entities
is defined and an array but just has no entries.
Upvotes: 1