Error Handling in HTTP Ajax Call using $fetch Javascript

两盒软妹~` 提交于 2019-12-11 15:25:59

问题


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/


回答1:


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
    }
  });


来源:https://stackoverflow.com/questions/45168087/error-handling-in-http-ajax-call-using-fetch-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!