typescript - 使用 fetch api 处理 500 响应

标签 typescript fetch aurelia

我们有以下对 fetch 的调用。

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

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

最佳答案

工作解决方案

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);
  });

详情

fetch() 返回包含 Response 对象的 PromisePromise 可以实现或拒绝。 Fulfillment 运行第一个 then(),返回它的 promise ,然后运行第二个 then()。拒绝在第一个 then() 上抛出并跳转到 catch()

引用资料

MDN - Promise

MDN - Checking that the fetch was successful

Google - Introduction to Fetch

关于typescript - 使用 fetch api 处理 500 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36225862/

相关文章:

javascript - Aurelia 和计算属性

javascript - 在 Aurelia Compose 的 View 模型中访问模型

Typescript - isEmpty 函数的通用类型保护

android - 如何从sqlite中一条一条地获取记录?

ios - 核心数据 : How to get data of entity in relationship?

javascript - Facebook 插件无法在内容/模板页面上运行

TypeScript问题如何在Chart.js和react-chartjs-2的自定义插件中传递参数

typescript - 我如何决定 @types/* 是进入 `dependencies` 还是 `devDependencies` ?

javascript - 用于从字符串创建 JSX 元素的正确 TypeScript 类型

Reactjs 使用凭据获取似乎不起作用