如何在提取错误中同时包含已解析的响应头和原始响应头 [英] How to include both a parsed response and original response headers in fetch errors

查看:80
本文介绍了如何在提取错误中同时包含已解析的响应头和原始响应头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下诺言链:

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

其中 checkstatus()检查是否请求成功,如果未成功,则返回错误。该错误将被捕获并返回。但是,问题是我想同时添加 response.statusText response.json()的结果错误。问题是,当我解析它时,我失去了链中的原始响应,因为我必须返回 response.json(),因为这是一个承诺。

Where checkstatus() checks if the request was successful, and returns an error if it wasn't. This error will be caught and returned. But, the problem is that I want to add the both response.statusText and the results of response.json() to the error. The problem is that when I parse it I lose the original response in the chain since I have to return response.json() because it's a promise.

这是checkstatus当前所做的:

This is what checkstatus does currently:

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

推荐答案

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

Here's my helper for sane fetch error handling, 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});
  }));

然后我将其替换为获取。

Which I then substitute for 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>

除非加载数据,否则有一个错误,可以直接替换。

It doesn't load the data unless there's an error, making it a direct replacement.

这篇关于如何在提取错误中同时包含已解析的响应头和原始响应头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆