【问题标题】:How to include both a parsed response and original response headers in fetch errors [duplicate]如何在获取错误中同时包含解析的响应和原始响应标头[重复]
【发布时间】:2017-05-21 04:53:22
【问题描述】:

我有以下承诺链:

return fetch(request)
  .then(checkStatus)
  .then(response => response.json())
  .then(json => ({ response: json }))
  .catch(error => ({ error }))

checkstatus() 检查请求是否成功,如果不成功则返回错误。此错误将被捕获并返回。但是,问题是我想将response.statusTextresponse.json() 的结果都添加到错误中。问题是,当我解析它时,我会丢失链中的原始响应,因为我必须返回 response.json(),因为它是一个承诺。

这是 checkstatus 当前所做的:

const checkStatus = response => {
  if (response.ok) return response

  const error = new Error('Response is not ok')

  // this works because the response hasn't been parsed yet
  if (response.statusText) error.message = response.statusText

  // an error response from our api will include errors, but these are
  // not available here since response.json() hasn't been called
  if (response.errors) error.errors = response.errors

  throw error
}

export default checkStatus

如何使用error.message = response.statusTexterror.errors = response.json().errors 返回错误?

【问题讨论】:

  • @Bergi 这个问题专门关于如何处理 fetch 中的错误,这可以说是不那么琐碎。因此,我认为这个问题值得提出自己的问题,不应将其作为更一般的组织问题的副本来关闭。
  • @jib "问题是,当我解析它时,我丢失了链中的原始响应,因为我必须返回 response.json(),因为它是一个承诺" 正是规范问题是关于
  • @Bergi 这里提出的解决方案有所不同,但我认为更清楚。

标签: javascript es6-promise fetch-api


【解决方案1】:

我使用新的 async/await 语法,因为它以更直观的方式读取:

 async fetchData(request) {
    try {
      const response = await fetch(request)
      const data = await response.json()

      // return the data if the response was ok
      if (response.ok) return { data }

      // otherwise return an error with the error data
      const error = new Error(response.statusText)
      if (data.errors) error.errors = data.errors

      throw error
    } catch (error) {
      return { error }
    }
  }

这使得处理fetch 返回的promise 以及response.json() 返回的promise 变得非常容易。

【讨论】:

    【解决方案2】:

    这是我的理智的fetch 错误处理助手,fetchOk

    let fetchOk = (...args) => fetch(...args)
      .then(res => res.ok ? res : res.json().then(data => {
        throw Object.assign(new Error(data.error_message), {name: res.statusText});
      }));
    

    然后我将其替换为 fetch。

    let fetchOk = (...args) => fetch(...args)
      .then(res => res.ok ? res : res.json().then(data => {
        throw Object.assign(new Error(data.error_message), {name: res.statusText});
      }));
    
    fetchOk("https://api.stackexchange.com/2.2/blah")
      .then(response => response.json())
      .catch(e => console.log(e)); // Bad Request: no method found with this name
    
    var console = { log: msg => div.innerHTML += msg + "<br>" };
    &lt;div id="div"&gt;&lt;/div&gt;

    除非出现错误,否则它不会加载数据,直接替换。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-13
      • 2011-06-24
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多