簡體   English   中英

使用異步等待獲取失敗時如何捕獲狀態代碼

[英]How to catch the status code when fetch fails using async await

語境

我將從使用Promises 異步/等待 獲取請求之一(我在Vuex action中使用了該請求,但這對於理解我的問題不是必需的)。

使用以下代碼,如果請求失敗,我可以根據響應的狀態代碼向最終用戶提供錯誤消息。

fetch("http://localhost:8000/api/v1/book", {
  headers: {
    Accept: "application/json"
  }
}).then(response => {
  if (!response.ok) {
    if (response.status === 429) {
      // displaying "wow, slow down mate"
    } else if (response.status === 403) {
      // displaying "hm, what about no?"
    } else {
      // displaying "dunno what happened \_(ツ)_/¯"   
    }

    throw new Error(response);
  } else {
    return response.json();
  }
}).then(books => {
  // storing my books in my Vuex store
})
.catch(error => {
  // storing my error onto Sentry
});

問題

使用async/await ,這就是我的代碼現在的樣子:

try {
  const response = await fetch("http://localhost:8000/api/v1/book", {
    headers: {
      Accept: "application/json"
    }
  });

  const books = await response.json();

  // storing my books
} catch(exception) {
  // storing my error onto Sentry
}

如果使用async/await失敗,如何確定響應返回的狀態碼?

如果我以錯誤的方式使用它,請不要猶豫,以更好的方式糾正我。

筆記

我做了一個JSFiddle來實時測試該問題。 隨時更新。

https://jsfiddle.net/180ruamk/

這將與您的then回調完全相同的代碼:

try {
  const response = await fetch("http://localhost:8000/api/v1/book", {
    headers: {
      Accept: "application/json"
    }
  });
  if (!response.ok) {
    if (response.status === 429) {
      // displaying "wow, slow down mate"
    } else if (response.status === 403) {
      // displaying "hm, what about no?"
    } else {
      // displaying "dunno what happened \_(ツ)_/¯"   
    }
    throw new Error(response);
  }
  const books = await response.json();

  // storing my books
} catch(exception) {
  // storing my error onto Sentry
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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