代码之家  ›  专栏  ›  技术社区  ›  shaan

即使api失败,fetch`then()`仍在执行

  •  0
  • shaan  · 技术社区  · 6 年前

    嗨,我做了一个像这样的获取包装器,我在组件中导入这个包装器,但是失败了 catch() 但是在组件中 then() 函数正在执行任何想法!!

     import { SERVER_URL } from '../configs/serverConfig';
    
      export default function callApi(api_url: string, method = 'get', data = null) {
    
    
        opts = {
          method: method,
          headers: {
            Authorization: 'Basic VFM0NjA2Omsuc3ZpbTg4',
            Accept: 'application/json',
            'Content-Type': 'application/json'
          }
        };
        if (data) {
          opts.data = JSON.stringify(data);
        }
        return fetchWrapper(api_url, opts);
      }
    
    
    
      function fetchWrapper (api_url: string, opts: any){
        let requestParamObj= {};
        if(opts.method.toLocaleLowerCase() === 'get'){
          requestParamObj = {
            method:opts.method
          }
        }
        else if(opts.method.toLocaleLowerCase() === 'post'){
          requestParamObj = {
            method: opts.method,
            headers: opts.headers,
            body: opts.data
          }
        }
    
    
        return (
          fetch(api_url, requestParamObj)
            .then((resp) => resp.json())
            .then(response => {
              return response;
            })
            .catch(error => {
              console.log('request failed', error);
              return error;
            })
        )
      }
    

    我把它叫做这样的组件

        callApi('/someURl', 'GET')
            .then((res) => {
            console.log('this get called even if api fails', res)
        }).catch((err) => {
            //TODO :: error handling at global level
            console.log('Some err', err)
        })
        }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Khaled Osman    6 年前

          fetch(api_url, requestParamObj)
            .then((resp) => resp.json())
            .then(response => {
              return response;
            })
            .catch(error => {
              console.log('request failed', error);
              throw error;
            })
    

    throw error 消费者捕获物将按预期返回。

    function handleErrors (response) {
      if (!response.ok) {
        console.log('ERROR: ' + response)
        throw Error(response.statusText)
      }
      return response
    }
    

    使用

    .then(handleErrors)
    
        2
  •  2
  •   Jed Richards    6 年前

    你有两件事出错了。

    第一,承诺 fetch 只返回拒绝到 catch 如果请求由于网络错误而失败,或者换句话说,请求永远不会到达服务器。如果你得到 任何 then .

    抓住 Promise.reject(value) 将链条踢回故障模式。

    你的包装最好看起来像:

    return (
      fetch(api_url, requestParamObj)
        .catch(error => Promise.reject(error)) // Handle network error
        .then(response => {
          if (!response.ok) {
            return Promise.reject(response) // Handle error responses HTTP 4XX, 5XX
          } else {
            return response.json() // Return success response HTTP 2XX, 3XX
          }
        })
    )
    
        3
  •  0
  •   Martin    6 年前

    fetch

    遇到网络错误,尽管这通常意味着权限问题或类似问题。 MDN

    在下面的示例中 ok 将记录:

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

    取来 提供 好 啊

    fetch("http://httpstat.us/500")
        .then(function(response) {
            if (!response.ok) {
                throw Error(response.statusText);
            }
            return response;
        }).then(function(response) {
            console.log("ok");
        }).catch(function(error) {
            console.log(error);
        });
    

    Source