使用提取API处理500个响应 [英] Handle a 500 response with the fetch api

查看:70
本文介绍了使用提取API处理500个响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们对fetch进行了以下调用.

We have the following call to fetch.

this.http.fetch('flasher', { method: 'post', body: jsonPayload })
    .then(response => response.json())
    .then(data => console.log(data));

这在我们收到200响应时有效,但是在我们收到500响应时则不记录任何内容到控制台.我们如何处理500?

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?

推荐答案

工作解决方案

thencatch结合使用即可.

Working Solution

Combining then with catch works.

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可以变为已实现或被拒绝.履行将运行第一个then(),返回其诺言,然后运行第二个then().拒绝引发第一个then()并跳到catch().

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().

MDN-承诺

MDN-检查是否成功

Google-提取简介

这篇关于使用提取API处理500个响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆