2017-05-27 311 views
0

仍然非常缺乏經驗,我試圖錯誤地處理「400錯誤請求」。JS:如何處理從API url返回的400錯誤請求錯誤

我有一個搜索欄的網站。
然後將輸入到搜索欄中的值放入一個返回對象的api url中。
無論何時輸入拼寫錯誤的搜索值,站點的控制檯都會爲api url返回一個「400 Bad Request」。
我還從api url請求中收到下面的錯誤對象。

{ 
    "meta": { 
     "code": 400, 
     "errorType": "failed_geocode", 
     "errorDetail": "Couldn't geocode param near: Jljjl", 
     "requestId": "59208ac96a6071641949481d" 
    }, 
    "response": {} 
} 

我想要做的就是使用條件語句像下面來處理這個錯誤:喜歡一個人的下方

try { 
    if (400 Bad Request) throw "incorrect"; 
} catch (err) { 
    document.getElementById('results').innerHTML = "Input is " + err; 
} 

我試過條件語句但似乎我無法訪問任何返回的錯誤對象的值:

if (object.meta.code === 400) 
if (object.meta.code !== 200) 
if (object === undefined) // or null or 0 

我怎樣才能把400錯誤請求錯誤進入「if語句」,或者是有另一種方式來處理這些錯誤?
感謝

+0

你找回JSON?您可能需要解析響應,例如'JSON.parse(object)',然後才能使用它作爲JavaScript對象。 –

+0

當你說「取回JSON」時,你能否詳細說明一下?在輸入值錯誤時,我只接收下面的對象,Thx很多:{「meta」:{「code」:400,「errorType」:「failed_geocode」,「errorDetail」:「無法將geocode參數靠近:「jljjl」,「requestId」:「59208ac96a6071641949481d」},「response」:{}} – TheBiscuit

+0

響應可能在字符串中,例如'「{」meta「:{」code「:400,」errorType「:」failed_geocode「 ,「errorDetai l」:「無法在接近Jljjl的地址解析參數」,「requestId」:「59208ac96a6071641949481d」},「response」:{}}「'。如果你用'JSON.parse(errorObject)'解析它,你會得到什麼? –

回答

0

剛上捎帶關閉m1kael這是我

window.fetch('https://api.foursquare.com/v2/venues/explore?v=20170324&near=Jljjl&query=study%20spot&limit=10&intent=browse&radius=100000&venuePhotos=1&client_id=XPQI2RJB3NMDT2JYQIMWDMGZSKRDQZX40NYIOKK02DXB1CVE&client_secret=UNHLLMUWXTEI3USTTN5DRJ02QDWQMHZQ5B22CFX0EY4JLEHO') 
.then(r => r.json()) 
.then(r => { 
    if (r.meta.code === 400) { 
    console.error('Error') 
    } else { 
    console.log(r) 
    } 
}) 
+0

謝謝。我看到我解析錯誤,第一次嘗試它。在我的網站中,我使用「$ .getJSON」函數獲取API對象。所以,既然你最後的迴應,我一直在試圖弄清楚如何在$ .getJSON函數內解析名爲「data」的對象。 – TheBiscuit

+0

看起來像'$ .getJSON'不允許你像400響應一樣處理錯誤。看起來你必須使用'$ .ajax'。這是一個代碼筆:https://codepen.io/arecvlohe/pen/mmYrqq?editors=1011 –

+0

錯誤回調的內部是你將使用你的條件邏輯來處理。 –

1

使用Fetch API,這可能是與以下操作來實現:

fetch(url) 
    .then((res) => { 
     if (res.status === 400) { 
      throw new Error('your error message here'); 
     } 
     return res.json(); 
    }) 
    .then(json => { 
     // handle response normally here 
    }) 
    .catch(ex => { 
     // handle errors here 
    }); 
+0

非常感謝您對此的幫助,我讓所有的工作都得到了解決。 – TheBiscuit

+0

不客氣,很高興這有幫助。 – m1kael