Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching a fetch error

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.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();
My assumption that any error should flow down callstack is correct or not? What is special about net::ERR_INTERNET_DISCONNECTED error?
like image 927
DrEarnest Avatar asked Mar 04 '26 13:03

DrEarnest


1 Answers

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.com/user.json");

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

        return response;

      } catch (e) {
        console.log(e);
      }
    }
like image 161
Pecata Avatar answered Mar 06 '26 04:03

Pecata



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!