0

I tried to handle the Network related issues in HTTP ajax call. So, I temporarily stopped the respective API's service in IIS and I tried to call the shut downed API - http://localhost:1000/GetData.

fetch("http://localhost:1000/GetData")
    .then(handleErrors)
    .then(function(response) {
        return response.Json();
    }).catch(function(error) {
        console.log(error);
    });

I tried the following code too

fetch("http://localhost:1000/GetData")
.then(response => {
        if(response) {
          if (response.status === 200) {
            alert('Super');
            return response.json();
          } else {
            alert('Hai');
            return '';
          } 
        } else {
          alert('Oooops');
          return '';
        }
      })
.catch(function(error) {
            console.log(error);
        });

But its failing and directly hitting the catch block without triggering any alert and its throwing an error. Moreover the response.json(); is in Success block, I don't know how its executed.

TypeError: response.json is not a function
Stack trace:
onFetchError/<@http://192.168.4.159:3000/app.0df2d27323cbbeada2cd.js:9946:13

Kindly assist me how to check the Status code and how to handle the Network error (i.e., Network Unavailable 404, etc.,)

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

alioguzhan
  • 7,657
  • 10
  • 46
  • 67
B.Balamanigandan
  • 4,713
  • 11
  • 68
  • 130

1 Answers1

0

Based on this issue on Github, you can try to identify error types in catch block instead. So, something like this may work for your case:

fetch("http://localhost:1000/GetData")
  .then(response => {
    alert("Super");
    return response.json();
  })
  .catch(err => {
    const errStatus = err.response ? err.response.status : 500;
    if (errStatus === 404){
      // do something
    } else {
      // do another thing
    }
  });
alioguzhan
  • 7,657
  • 10
  • 46
  • 67
  • 1
    Its failing... Currently it triggers the `HTTP OPTIONS`, its not returning any response back to the browser if the requesting Server is offline. I posted a details in my question https://stackoverflow.com/questions/45182002/handling-of-failure-status-in-http-options-ajax-call –  Jul 19 '17 at 05:57