小编典典

获取:使用JSON错误对象拒绝Promise

javascript

我有一个HTTP API,无论成功还是失败,它都会返回JSON数据。

失败示例如下所示:

~ ◆ http get http://localhost:5000/api/isbn/2266202022 
HTTP/1.1 400 BAD REQUEST
Content-Length: 171
Content-Type: application/json
Server: TornadoServer/4.0

{
    "message": "There was an issue with at least some of the supplied values.", 
    "payload": {
        "isbn": "Could not find match for ISBN."
    }, 
    "type": "validation"
}

我想要在JavaScript代码中实现的是这样的:

fetch(url)
  .then((resp) => {
     if (resp.status >= 200 && resp.status < 300) {
       return resp.json();
     } else {
       // This does not work, since the Promise returned by `json()` is never fulfilled
       return Promise.reject(resp.json());
     }
   })
   .catch((error) => {
     // Do something with the error object
   }

阅读 270

收藏
2020-05-01

共1个答案

小编典典

 // This does not work, since the Promise returned by `json()` is never

fulfilled
return Promise.reject(resp.json());

好吧,resp.json诺言 得到兑现,只是Promise.reject不等待它,而是立即 兑现诺言

我假设您宁愿执行以下操作:

fetch(url).then((resp) => {
  let json = resp.json(); // there's always a body
  if (resp.status >= 200 && resp.status < 300) {
    return json;
  } else {
    return json.then(Promise.reject.bind(Promise));
  }
})

(或明确写出)

    return json.then(err => {throw err;});
2020-05-01