【问题标题】:How to handle API errors efficiently?如何有效地处理 API 错误?
【发布时间】:2018-12-20 06:33:52
【问题描述】:

当一切顺利时,它会返回一个带有status: 'OK' 的对象 如果出现问题,它会返回status: 'FAILED', 由于这种方法,我需要处理 try 和 catch 块中的错误,例如

try {
  const {data} = await axios.post(....);

  if(data.status === 'OK') {
    // do something and return 
  }

  //handle error
} catch(e) {
  // handle Error Again
}

如您所见,我需要处理两次错误。我正在使用 redux-saga,所以我为 API 创建了另一个文件并在 saga 中像这样处理它:

yield = ...my api

// then 

if (data.status === 'OK') {
  // do something and return 
} 

等等...我的最终目标是保持我的 sagas 干净。有什么方法可以调用 API 然后检查 API 文件中的状态?它应该转到 saga 的 catch 块,所以我只需要处理我的 catch 块中的错误?

我的最终目标是这样的

function* doSomethng() {
  try {
    yield callapi...
    //do something
  } catch(e) {
    // handle errors and even if the api status is 200
    // but it returns an object with status 'FAILED' it should come here
  }
}

【问题讨论】:

    标签: javascript reactjs react-native axios redux-saga


    【解决方案1】:

    您可以创建一个包装函数,该函数将向承诺链添加检查并抛出错误状态。

    const checkStatus = async (promise) => {
        const result = await promise;
        if (!result || result.status === 'FAILED') throw new Error('Request failed');
        return result;
    }
    
    function* doSomething() {
        try {
            yield checkStatus(callapi(...));
            //do something
        } catch(e) {
            // ...
        }
    }
    

    您还可以在callapi 函数本身中“隐藏” checkStatus 调用。

    【讨论】:

      猜你喜欢
      • 2012-01-29
      • 1970-01-01
      • 2018-05-16
      • 2019-05-13
      • 1970-01-01
      • 2012-11-15
      • 2017-08-04
      • 2017-02-02
      • 1970-01-01
      相关资源
      最近更新 更多