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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:22:39  来源:igfitidea点击:

Handle a 500 response with the fetch api

typescriptfetchaurelia

提问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 thenwith catchworks.

结合thencatch工程。

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 Promisecontaining a Responseobject. The Promisecan 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 - Promise

MDN - 承诺

MDN - Checking that the fetch was successful

MDN - 检查获取是否成功

Google - Introduction to Fetch

Google - Fetch 简介