簡體   English   中英

捕獲獲取錯誤

[英]Catching a fetch error

我的理解是,在調用堆棧中的任何地方拋出錯誤的一段代碼都可以在最終的 catch 塊中被捕獲。 對於獲取錯誤,當沒有互聯網可用時,當我在 callCallAPI 中創建 APIwithoutCatch 時,不會捕獲錯誤。 而 APIwithCatch 捕獲自己的錯誤。 所有其他錯誤,例如 404,在我想要的兩個地方都被捕獲。

 async function APIwithcatch() { try { var response = await fetch("http://wwww.dfdfdf.com/user.json"); return response; } catch (e) { console.log(e); } } async function APIwithoutcatch() { var response = await fetch("http://wwww.dfdfdf.com/user.json"); return response; } function callCallAPI() { try { // return APIwithcatch(); return APIwithoutcatch(); } catch (e) { console.log(e); } } callCallAPI();
我認為任何錯誤都應該流向調用堆棧的假設是否正確? net::ERR_INTERNET_DISCONNECTED 錯誤有什么特別之處?

APIwithoutcatch是一個async function ——它不會拋出異常,而是會拒絕它返回的承諾。 您需要使用thenawait語法await承諾(就像您在APIwithcatch await fetch APIwithcatch ):

async function API() {
  return fetch("http://wwww.example.com/user.json");
}

function callAPI() {
  try {
    await API();
  } catch (e) {
    console.log(e);
  }
}
callAPI();

根據 MDN, fetch() API 僅在“遇到網絡錯誤時才會拒絕承諾,盡管這通常意味着權限問題或類似問題”。 基本上 fetch() 只會在用戶離線時拒絕承諾,或者發生一些不太可能的網絡錯誤,例如 DNS 查找失敗。

但是 fetch 提供了一個 ok 標志,我們可以使用它來檢查 HTTP 狀態代碼是否成功並throw用戶定義的異常

await response.json()將從await response.json()提取 JSON 正文內容,以便我們可以throwthrow .catch塊。

    async function APIwithcatch() {
      try {
        var response = await fetch("http://wwww.dfdfdf.com/user.json");

        if (!response.ok) throw await response.json();

        return response;

      } catch (e) {
        console.log(e);
      }
    }

UPD:遇到了你的問題,不幸的是你不能像你的代碼那樣捕捉錯誤

Fetch 是異步的,因此您不能使用try {} catch {}構造,而是使用.then().catch()

async function APIwithoutcatch() {
  var response = await fetch("http://wwww.dfdfdf.com/user.json");
  return response;
}

function callCallAPI() {
  return APIwithoutcatch()
    .then((data) => {
      console.log(data)
    })
    .catch((e) => {
      console.log(e)
    })
}

callCallAPI();

暫無
暫無

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

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