猿问

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

我有一个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

   }


MM们
浏览 615回答 3
3回答

倚天杖

&nbsp;// This does not work, since the Promise returned by `json()` is never fulfilledreturn Promise.reject(resp.json());好吧,resp.json诺言将得到兑现,只是Promise.reject不等待它,而是立即兑现诺言。我假设您宁愿执行以下操作:fetch(url).then((resp) => {&nbsp; let json = resp.json(); // there's always a body&nbsp; if (resp.status >= 200 && resp.status < 300) {&nbsp; &nbsp; return json;&nbsp; } else {&nbsp; &nbsp; return json.then(Promise.reject.bind(Promise));&nbsp; }})(或明确写出)&nbsp; &nbsp; return json.then(err => {throw err;});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答