簡體   English   中英

Javascript 在控制台和回調消息中捕獲錯誤

[英]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)
}

根據結果​​數據結構的可靠性,您還可以檢查nullundefined值。 但是對於這個特定的錯誤,它看起來像定義了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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM