使用fetch api处理500响应

Sha*_*tin 8 fetch typescript aurelia

我们有以下电话fetch.

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

当我们收到200响应但在收到500响应时没有记录到控制台时,这种方法有效.我们如何处理500?

Sha*_*tin 14

工作方案

结合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);
  });
Run Code Online (Sandbox Code Playgroud)

细节

fetch()返回Promise包含Response对象的内容.本Promise可以成为既满足或拒绝.Fulfillment运行第一个then(),返回其承诺,并运行第二个then().拒绝抛出第一个then()并跳转到catch().

参考

MDN - 承诺

MDN - 检查提取是否成功

Google - Fetch简介

  • 这可能不会做你想做的。这将导致误报(如果服务器在 4xx-5xx 状态下返回文本错误响应)或提取文本将失败,它将记录对 `response.text()` 调用的错误,这将最可能没有帮助。您应该改为在第一个 `then` 中明确检查状态代码或 `res.ok` 并做出相应的响应。请参阅[此处](https://www.tjvantoll.com/2015/09/13/fetch-and-errors/)。 (3认同)