【问题标题】:How to cleanly handle an expected error in fetch?如何干净地处理提取中的预期错误?
【发布时间】:2018-05-17 19:58:08
【问题描述】:

我需要通过fetch() 调用查询一些数据,但我不确定请求是否会成功,HTTP 方面:当服务器启动时,URL 可能(合法地)访问一个不存在的页面。

我想干净利落地处理此案,我目前的方法是引发异常:

// the URL is just an example, I did not have anything CORS-enabled (and unavailable) handy, thus the no-cors mode
fetch(`https://cdnjs.com/libraries/sdfsdfsfsdfsdfsdfdf`, {
    mode: 'no-cors'
  })
  .then(r => {
    if (!r.ok) {
      console.log("page does not exist")
      throw Error();
    }
    // if the page exists, it will return JSON data
    return r.json();
  })
  .then(r => {
    console.log(r)
    // things with the JSON happen here
  })
  .catch(err => null)

我希望在Page does not exist 之后只返回return,但是(空)返回会被下一个then() 捕获。

当请求的 URL 不可用时,这是退出 fetch() 的正确方法吗?

【问题讨论】:

  • 您希望在每种情况下如何处理这些数据?即,如果你得到 JSON,你想对它做什么,如果有错误你想做什么?

标签: javascript error-handling fetch-api


【解决方案1】:

是的,看起来差不多。我建议为您的 then 使用函数。 它使 fetch 更紧凑,更易于阅读。

const url = 'some url';
fetch(url)
  .then(handleErrors)
  .then(parseJSON)
  .then(update)
  .catch(displayErrors);
  
function handleErrors(res){
  if(!res.ok){
    throw Error(`${res.status}: Couldn't load URL.`);
  }
  return res;
}

function parseJSON (res){
  return res.json().then(function(parsedData){
    return parsedData.results[0];
  })
}

function update (){
    //do something with the data
}

function displayErrors(err){
  console.log(err);
}

【讨论】:

    猜你喜欢
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    相关资源
    最近更新 更多