如何在获取错误中包含已解析的响应和原始响应 headers

How to include both a parsed response and original response headers in fetch errors

我有以下承诺链:

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

其中 checkstatus() 检查请求是否成功,return 如果不成功则报错。此错误将被捕获并 returned。但是,问题是我想将 response.statusTextresponse.json() 的结果都添加到错误中。问题是,当我解析它时,我丢失了链中的原始响应,因为我必须 return 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

如何 return error.message = response.statusTexterror.errors = response.json().errors 出错?

我使用新的 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 returns 和 response.json() returns.

的承诺变得非常容易

这是我理智的 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>" };
<div id="div"></div>

它不会加载数据,除非出现错误,使其成为直接替换。