Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
732 views
in Technique[技术] by (71.8m points)

rxjs - ngrx effects error handling

I have a very basic question concerning @ngrx effects: How to ignore an error that happens during the execution of an effect such that it doesn't affect future effect execution?

My situation is as follows: I have an action (LOGIN) and an effect listening to that action. If an error happens inside this effect, I want to ignore it. When LOGIN is dispatched a second time after this error, the effect should be executed a second time.

My first attempt to do this was:

  @Effect()
  login$ = this.actions$
    .ofType('LOGIN')
    .flatMap(async () => {
      console.debug('LOGIN');
      // throw an error
      let x = [];x[0]();
    })
    .catch(err => {
      console.error('Error at login', err);
      return Observable.empty();
    });

Dispatching LOGIN the first time throws and catches the error, as expected. However, if I dispatch LOGIN a second time afterwards, nothing happens; the effect is not executed.

Therefore I tried the following:

    .catch(err => {
      return this.login$;
    });

, but this results in an endless loop... Do you know how to catch the error without preventing effect execution afterwards?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The ngrx infrastructure subscribes to the effect via the provider imported into the app's NgModule using EffectsModule.run.

When the observable errors and catch returns a empty obervable, the composed observable completes and its subscribers are unsubscribed - that's part of the Observable Contract. And that's the reason you see no further handling of LOGIN actions in your effect. The effect is unsubscribed on completion and the ngrx infrastructure does not re-subscribe.

Typically, you would have the error handling inside the flatMap (now called mergeMap):

import { Actions, Effect, toPayload } from "@ngrx/effects";

@Effect()
login$ = this.actions$
  .ofType('LOGIN')
  .map(toPayload)
  .flatMap(payload => Observable
    .from(Promise.reject('Boom!'))
    .catch(error => {
      console.error('Error at login', error);
      return Observable.empty();
    })
  });

The catch composed into the inner observable will see an empty observable flattened/merged into the effect, so no action will be emitted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...