2

I am making a network request in a react native project using the fetch api. It works well in normal conditions but when I am offline the catch block just gives as result of the logging error but when I do err.message I get "Network request failed" I was hoping to get some codes. How can I get the possible codes to check for in anticipation of a network failure?

I tried logging the entire err and I get nothing but when I use err.message I get "Network request failed"

fetch(url, {
    method: 'GET',
    headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    }
})
.then((response) => response.json())
.then((responseJson) => {
     this.setState({ procesing: false });
     this.setState({ music: responseJson });

})
.catch(err => {
     console.log(err)
     console.log(err.message)
})

for console.log(err), I expected to have and error code and the corresponding message but I get nothing

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
harisu
  • 1,376
  • 8
  • 17

2 Answers2

0

As per this answer, you can use a function to stringify the error:

var stringifyError = function(err, filter, space) {
  var plainObject = {};
  Object.getOwnPropertyNames(err).forEach(function(key) {
    plainObject[key] = err[key];
  });
  return JSON.stringify(plainObject, filter, space);
};

stringifyError(someError, null, '\t');
Yannick K
  • 4,887
  • 3
  • 11
  • 21
0

If I understand correctly, you are expecting error for some testing purposes. First of all, try to console.log any string, like

console.log('error');

If nothing happens (I am pretty sure it won't), try throwing error if response is not okay.

function handleErrors(response) {
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response;
}

fetch("http://httpstat.us/500")
    .then(handleErrors)
    .then(function(response) {
        console.log("ok");
    }).catch(function(error) {
        console.log(error);
    });

Source: https://www.tjvantoll.com/2015/09/13/fetch-and-errors/