编程语言
首页 > 编程语言> > javascript – 如何在获取错误中包含已解析的响应和原始响应标头

javascript – 如何在获取错误中包含已解析的响应和原始响应标头

作者:互联网

参见英文答案 > How do I access previous promise results in a .then() chain?                                    15个
我有以下承诺链:

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

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

这就是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.statusText和error.errors = response.json().errors返回错误?

解决方法:

这是我对sane 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>

除非出现错误,否则它不会加载数据,从而使其成为直接替换.

标签:fetch-api,javascript,es6-promise
来源: https://codeday.me/bug/20191009/1876683.html