0

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.'

1

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.