如何在 fetch 的 then() 中捕获 json 文本

How to capture the json text inside fetch's then()

我这样称呼fetch

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

我调用的url总是return一个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;
}

我已经检查过这个问题,但它并没有真正满足我的需要。此外,根据评论,接受的答案似乎并没有完全解决 OP 的问题。

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

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

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

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

那应该做你想做的事