【问题标题】:How to capture the json text inside fetch's then()如何在 fetch 的 then() 中捕获 json 文本
【发布时间】:2017-09-02 07:00:04
【问题描述】:

我就是这样称呼fetch

fetchOpts = {...}
return fetch(url, fetchOpts)
    .then(checkStatus)

我调用的url总是会返回一个json数据,即使是在错误的情况下:

{error_message:"Encountered issue with update"
status:"error",
status_code:400}

我想获取error_message 字段值并传递给Error 构造函数。

在 checkStatus 内部,它以这种方式处理异常:

function checkStatus(response) {
  let error = null;

  if (!response.headers.get('Content-Type').includes('application/json')) {
    error = new Error(response.statusText);
    error.response = response;
    throw error;
  }

  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  if (response.ok) {
    return response;
  }
  const jsonData = response.json() ; // <- `jsonData` is a promise
  error = new Error(/* How to extract error_message from json data? */);
  error.response = response;
  throw error;
}

我已经检查过这个问题,但它并没有真正解决我的需求fetch: Reject promise with JSON error object。此外,根据 cmets,接受的答案似乎不能完全解决 OP 的问题。

【问题讨论】:

    标签: javascript ecmascript-6 promise fetch-api


    【解决方案1】:

    我可能误解了这个问题,但 error_message 成员作为 promise 返回的数据对象的属性公开,对吗?所以看起来你可以这样做:

    response.json()
    .then(jsonData => {
      if (jsonData.error_message) {
        error = new Error(jsonData.error_message)
      }
    }
    

    【讨论】:

      【解决方案2】:

      如果您将最后一段代码更改为

      return response.json().then(json => {
          error = new Error(json.error_message);
          error.response = response;
          throw error;
      }
      

      这应该做你想要的

      【讨论】:

        猜你喜欢
        • 2016-10-30
        • 1970-01-01
        • 2021-12-09
        • 2022-10-12
        • 1970-01-01
        • 2017-01-13
        • 1970-01-01
        • 2018-06-28
        • 2013-04-19
        相关资源
        最近更新 更多