最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Catching a fetch error - Stack Overflow

programmeradmin6浏览0评论

My understanding is that a piece of code throwing error anywhere in callstack can be caught at final catch block. for fetch error, when no internet is available, when I make APIwithoutCatch in callCallAPI, error is not caught. while APIwithCatch catches its own error. All other errors e.g. 404, are caught at both places, wherever I want.

async function APIwithcatch() {
  try {
    var response = await fetch(".json");
    return response;
  } catch (e) {
    console.log(e);
  }
}

async function APIwithoutcatch() {
  var response = await fetch(".json");
  return response;
}

function callCallAPI() {
  try {
    // return APIwithcatch();
    return APIwithoutcatch();
  } catch (e) {
    console.log(e);
  }
}
callCallAPI();

My understanding is that a piece of code throwing error anywhere in callstack can be caught at final catch block. for fetch error, when no internet is available, when I make APIwithoutCatch in callCallAPI, error is not caught. while APIwithCatch catches its own error. All other errors e.g. 404, are caught at both places, wherever I want.

async function APIwithcatch() {
  try {
    var response = await fetch("http://wwww.dfdfdf./user.json");
    return response;
  } catch (e) {
    console.log(e);
  }
}

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

function callCallAPI() {
  try {
    // return APIwithcatch();
    return APIwithoutcatch();
  } catch (e) {
    console.log(e);
  }
}
callCallAPI();
My assumption that any error should flow down callstack is correct or not? What is special about net::ERR_INTERNET_DISCONNECTED error?

Share Improve this question edited Aug 23, 2018 at 6:39 DrEarnest asked Aug 22, 2018 at 10:01 DrEarnestDrEarnest 8852 gold badges14 silver badges29 bronze badges 6
  • js fetch(url, requestConfig) .then(response => handleApiResponse(response, ...args)) .catch(err => console.error(err)); This code catch typeError: Failed to fetch, when trying without internet. js try { var response = fetch(url, requestConfig) return response } catch(e) { console.log(e) } This throw uncaughtPromiseRejection Error. – DrEarnest Commented Aug 23, 2018 at 5:56
  • "All other errors e.g. 404, are caught at both places" - you are not handling status codes anywhere, what makes you think that is an error? (Sure a 404 network request shows up in console separately, but you're not logging it from the code you posted) – Bergi Commented Aug 23, 2018 at 9:30
  • Here is a gist that I created out of code that I am using in my project. It might not work but will give you more details. gist.github./skant09/e85416c0b7fc26627989dd9f6c292984 – DrEarnest Commented Aug 23, 2018 at 17:33
  • I don't see how that relates to the code in your question. How are you calling postAPI, what are you expecting, what does not work when you get which response? – Bergi Commented Aug 24, 2018 at 8:00
  • When I call postApi, and internet is not there, I am unable to catch the error. – DrEarnest Commented Aug 24, 2018 at 8:11
 |  Show 1 more ment

3 Answers 3

Reset to default 9

Per MDN, the fetch() API only rejects a promise when a “network error is encountered, although this usually means permissions issues or similar.” Basically fetch() will only reject a promise if the user is offline, or some unlikely networking error occurs, such a DNS lookup failure.

However fetch provides a ok flag that we can use to check if the HTTP status code is a success or not and throw a user-defined exception

await response.json() will extract the JSON body content from the response so we can throw it to the .catch block.

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

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

        return response;

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

APIwithoutcatch is an async function - it doesn't throw an exception but rather will reject the promise that it returns. You need to wait for the promise, either with then or await syntax (just like you did await the fetch within APIwithcatch):

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

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

UPD: got your problem, unfortunately you can't catch an error like in your code

Fetch is asynchronous, so you mustn't use try {} catch {} construction, use .then().catch() instead:

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

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

callCallAPI();
发布评论

评论列表(0)

  1. 暂无评论