RxJS:主题错误渗透到订阅者

时间:2018-06-08 17:45:32

标签: typescript rxjs reactive-programming

我的情况是Subject正在返回错误,但订阅Observable的{​​{1}}的错误方法正在执行,即使订阅Subject {1}}不会失败并返回错误。像这样:

Observable

在此代码中,正在执行this.createPayment$ = this.wizard$.pipe( switchMap((wizard) => willReturnAnErrorObservable()), share() ); this. handleSuccessSubscription = this.createPayment$.pipe( filter((someEvent: SomeEvent) => event.succeeded), switchMap((someEvent: SomeEvent) => // this is never called because the filter above does not pass doesNotFailObservable() ) ).subscribe((confirmedPayment: PaymentDeviceEvent) => { // not important }, (error) => { // this error block is still being called, even though the this. // handleSuccessSubscription switchMap is not executed, because the // this.handleSuccessSubscription$ above returns an error }); 的错误方法,即使createPaymentSuccessfulSubscription返回正常,这是因为'外部' switchMap正在抛出错误。

有没有办法阻止订阅者也收到错误?它并不重要,因为我可以对返回的Subject进行过滤,以确定是否需要在此处理;但它有点臭,我希望这个错误块不会被执行。

1 个答案:

答案 0 :(得分:0)

在传递给最终消费者

之前,您应该捕获错误并处理它们
import { of } from 'rxjs';
import { catchError, switchMap, share } from 'rxjs/operators';

this.createPayment$ = this.wizard$.pipe(
  switchMap((wizard) => willReturnAnErrorObservable()),
  catchError((error) => of(console.log('log error', error))),
  share(),
);