typescript 使用 fetch api 处理 500 响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36225862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Handle a 500 response with the fetch api
提问by Shaun Luttin
We have the following call to fetch
.
我们有以下调用fetch
.
this.http.fetch('flasher', { method: 'post', body: jsonPayload })
.then(response => response.json())
.then(data => console.log(data));
This works when we receive a 200 response but logs nothing to the console when we receive a 500 response. How do we handle a 500?
这在我们收到 200 响应时有效,但在我们收到 500 响应时不会向控制台记录任何内容。我们如何处理500?
回答by Shaun Luttin
Working Solution
工作解决方案
Combining then
with catch
works.
结合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);
});
Details
细节
fetch()
returns a Promise
containing a Response
object. The Promise
can become either fulfilled or rejected. Fulfillment runs the first then()
, returns its promise, and runs the second then()
. Rejection throws on the first then()
and jumps to the catch()
.
fetch()
返回一个Promise
包含一个Response
对象。本Promise
可以成为既满足或拒绝。Fulfillment 运行第一个then()
,返回其承诺,然后运行第二个then()
。拒绝抛出第一个then()
并跳转到catch()
.
References
参考
MDN - Checking that the fetch was successful