2017-09-06 27 views
-2

處理錯誤處理問題,我需要根據返回的狀態代碼捕獲錯誤。另外,我需要獲取響應的主體以獲取特定的錯誤消息。我創建了一個粗糙的腳本,內容如下:使用帶狀態500的提取API讀取json內容的更好方法

let status = 200; 
return fetch('/someurl',{ credentials: 'include' }) 
     .then(res => { 
      if(!res.ok) { 
       status = res.status; 
      } 
      return res.json(); 
     }) 
     .then(json => { 
      if(status < 200 || status >= 300) { 
       notifyError(status, json); 
      } 
      treatResponse(json); 
     }) 
     .catch(err => notifyError(err)); 

此代碼的工作如我所料,但它不是什麼我會在代碼質量方面期待,因爲我使用了一個全局變量旁邊的通知,然後在發生了什麼以前那麼...很醜陋。

我認爲我的代碼反映了我是新來的api和這個承諾的東西,我瞭解但我不熟悉的事實。

那麼有人可以更好地吸收東西嗎?

感謝

+1

' res.json'是異步函數?除了這個'notifyError'看起來很奇怪,它接受'status'和'json' **或者**錯誤...更好的是隻接受錯誤,但是可能有'status'和'json'字段。 – alexmac

+0

@alexmac我同意你關於'notifyError()'的奇怪簽名,但回答你的問題,是的,'res.json()'返回一個承諾。 –

回答

0

你可以將其轉換爲這一點,通過使用Promise.all()傳遞一個承諾,承諾的數組:

return fetch('/someurl', { credentials: 'include' }) 
    .then(res => Promise.all([res.status, res.json()])) 
    .then(([status, json]) => { 
    if (status < 200 || status >= 300) { 
     notifyError(status, json) 
    } 

    treatResponse(json) 
    }) 
    .catch(err => notifyError(err)) 
+0

這是一個巧妙的把戲 –

+0

我想你應該添加'return treatResponse(json)',因爲如果它返回一些東西,這個結果將不會被使用。 – alexmac

+0

@alexmac告訴OP,而不是我。我只是重複所需的改進給定的代碼。 –

-2

簡單地拋出錯誤,趕上這個錯誤在catch塊級

return fetch('/someurl',{ credentials: 'include' }) 
     .then(res => { 
      if(!res.ok) { 
       throw Error('something'); 
      } 
      return res.json(); 
     }) 
     .then(json => { 
      if(status < 200 || status >= 300) { 
       throw Error('something othere'); 
      } 
      treatResponse(json); 
     }) 
     .catch(err => notifyError(err)); 

可能是這個幫助 - read

+0

也是乾淨的。 –

+0

這不會重現所需的代碼,當錯誤是500響應時,'notifyError()'不會傳遞'status'和'json'。 –