RxJS 5:如何在捕获时获取 statusCode

RxJS 5: how to get statusCode on catch

如何从 RxJS 中失败的 ajax 调用中取回状态代码,以便我决定如何处理它?

import { ajax } from 'rxjs/observable/dom/ajax'

ajax('https://my.url')
  .map(xhr => console.log('woo', xhr.response))
  .catch(err => console.log('status code??'))

err 响应中有一些字段,其中之一是 status,但它始终是 0,与 statusCode 无关。

根据文档:https://github.com/Reactive-Extensions/RxJS-DOM/blob/master/doc/operators/ajax.md

您可以像下面这样操作:

ajax('https://my.url')
  .map(xhr => console.log('woo', xhr.response))
  .catch((err, status) => console.log(status))

编辑:

我错过了您看到 error.status 的事实,所以问题只是为什么它为零。

这是浏览器的问题。 It's zero by default,并且只有在请求实际返回时才会更改。如果由于任何原因它没有完成,它仍然为零。这包括中止的请求、CORS 问题、离线、DNS 问题和任何其他网络错误。这是有道理的,因为大多数情况下没有 HTTP 代码。 CORS 请求错误本身可能有 401(或其他代码),但浏览器不会以编程方式向您公开它。

不幸的是,发生这种情况时,您无法通过编程方式了解是什么原因造成的。您可以检查 navigator.onLine,如果它是假的,可能会推断它是由于未连接到互联网造成的,尽管这不是 100% 可靠。

在其他情况下,您以编程方式搞砸了。没有带有解释或其他方式的错误消息 属性。错误的真正原因通常是在开发控制台中(所以在那里检查),但出于安全原因无法以编程方式访问。

这里有一些关于此的额外资源:


在 v5 中(至少在 v4 中也是如此),状态作为提供的错误对象的顶级 属性 status 可用:

import { ajax } from 'rxjs/observable/dom/ajax'

ajax('https://my.url')
  .map(xhr => console.log('woo', xhr.response))
  .catch(err => {
    console.log('status code', error.status);
    // also available as error.xhr.status (inside the raw XMLHttpRequest object)
    return Observable.empty(); // switch to an empty stream i.e. swallow error
  });

请注意,catch 用于捕获错误 ,然后切换到您必须 return 的另一个 Observable。所以必须处理错误。如果不想处理错误,只想记录错误,可以使用 do:

ajax('https://my.url')
  .map(xhr => console.log('woo', xhr.response))
  .do({ error: err => console.log('status code', err.status) })