Typescript(或JavaScript)提取API async/等待错误处理



我想使用async/axyt语法,fetch api并想要实现以下行为:

如果响应不是200个,请记录响应,不要扔任何东西并返回null。如果响应是200,请返回响应。

但是!Fetch API对与404、505或200不同的所有事物都提供了例外,最后我得到了这样的丑陋结构:

...
try{
 let response = await fetch(url, {method: 'GET', mode: 'cors'});
 if(response.status != 200){
    console.log('Failed to get what I want, got status: ' + response.status);
    return null;
 }
catch(e){
  console.log('error bla bla');
  return null;
}
...

是否有更优雅的方法可以实现相同的方法?

来自mdn:

当网络错误是 遇到或CORS在服务器端被错误配置,尽管这是 通常意味着许可问题或类似的问题 - 404不构成 例如,网络错误。

和:

从fetch((返回的承诺不会在HTTP错误状态上拒绝 即使响应是http 404或500。相反,它也会解决 通常(确定状态设置为false(,并且只会拒绝 网络故障或如果有任何阻止请求完成。

正如Garry在他的回答中所说的那样,我建议创建一个中间件来处理不成功的答复,或者如果状态不是200,或者response.ok是错误的。

示例(使用https://httpstat.us/(:

async function getData() {
  try {
    let response = await fetch('https://httpstat.us/401', {
      method: 'GET',
      mode: 'cors'
    });
    if (!response.ok) throw response.statusText;
    console.log('Dataaa');
    return response
  } catch (e) {
    console.error(e);
    return null
  }
}
getData()

提取不会基于状态代码投掷。如果存在网络错误,例如无法到达服务器,它将投掷。这是在获取规格中定义的

以下是获取各种状态代码的示例

async function getit(status) {
  let url = 'https://httpstat.us/' + status
  try {
    let response = await fetch(url, {
      method: 'GET',
      mode: 'cors'
    });
    if (response.ok) {
      console.log("Got what we wanted")
    } else {
      console.log('Failed to get what I want, got status: ' + response.status);
    }
    return "okay";
  } catch (e) {
    console.log('A real error!');
    return "network error";
  }
}
getit(200).then(console.log)
// error codes
getit(400).then(console.log)
getit(503).then(console.log)
getit(401).then(console.log)

只要收到HTTP响应,就不应投掷。

(您的代码中确实有一个错别字 - 您缺少if (response.status != 200) {上的关闭括号,但这应该导致语法错误,而不是拒绝的承诺(

我会说创建一个中间器皿,并将中间件功能称为fetch((。然后(中间件(。这样,每个请求都将始终使用中间件方法,您可以在一个地方添加您的检查。

如果您可以使用fetch()的替代方案,则AXIOS似乎具有清洁/可配置的错误处理。实际上,默认设置与您的用例完全匹配。(如果状态代码2xx除了其他任何内容(:

try {
    let response = await axios.get(url, {mode: 'cors'});
    return response;
} catch (error) {
    if (error.response) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        console.log('Failed to get what I want, got status: ' + error.response.status);
    } else {
        console.log('error bla bla');
    }    
    return null;  
}

(顺便说一句,用Axios获得JSON只是一个步骤,而r = await fetch()的两个步骤,然后是r.json()(

最新更新