【问题标题】:Handle a 500 response with the fetch api使用 fetch api 处理 500 响应
【发布时间】:2016-07-13 13:25:04
【问题描述】:
我们有以下电话给fetch。
this.http.fetch('flasher', { method: 'post', body: jsonPayload })
.then(response => response.json())
.then(data => console.log(data));
这在我们收到 200 响应时有效,但在收到 500 响应时不会向控制台记录任何内容。我们如何处理500?
【问题讨论】:
标签:
typescript
fetch
aurelia
【解决方案1】:
工作解决方案
将then 与catch 结合使用。
fetch('http://some-site.com/api/some.json')
.then(function(response) { // first then()
if(response.ok)
{
return response.text();
}
throw new Error('Something went wrong.');
})
.then(function(text) { // second then()
console.log('Request successful', text);
})
.catch(function(error) { // catch
console.log('Request failed', error);
});
详情
fetch() 返回一个包含Response 对象的Promise。 Promise 可以变为已完成或拒绝。 Fulfillment 运行第一个then(),返回它的promise,然后运行第二个then()。拒绝抛出第一个 then() 并跳转到 catch()。
参考文献
MDN - Promise
MDN - Checking that the fetch was successful
Google - Introduction to Fetch
【讨论】:
-
这可能不会如你所愿。这将导致误报(如果服务器在 4xx-5xx 状态下返回文本错误响应),或者提取文本将失败,并将记录调用 response.text() 的错误,这很可能没有帮助。您应该在第一个 then 中明确检查状态代码或 res.ok 并做出相应的响应。见here。
-