LearnToday
LearnToday

Reputation: 2902

How to catch error with ngrx

I am trying to catch an error with ngrx and angularfire2 firetore.

Here is the effect

@Effect()
        delete$: Observable<Action> = this.actions$
        .ofType(actions.DELETE)
        .map((action: actions.Delete) => action.id)
        .mergeMap(id => 
         of(this.afs.doc<Collection(`collections/${id}`).delete()))
        .map(() =>  new actions.Success())
        .catch(err => of (new actions.Fail(err.message )));

and actions:

export class Success implements Action {
  readonly type = SUCCESS;
  constructor() {
    console.log('success')
   }
}


export class Fail implements Action {
  readonly type = ERROR;

  constructor(public payload: any) {
    console.log('failed');
 }
}

I keep getting success even if the action is not completed. What is the good way to do this?

Upvotes: 0

Views: 698

Answers (1)

vince
vince

Reputation: 8306

Currently, this code is trying to catch errors on the entire stream, rather than the inner observable that matters.

Try this:

@Effect delete$: Observable<Action> = this.action$
  .ofType(actions.DELETE)
  .map((action: actions.Delete) => action.id)
  .mergeMap(id => { 
    return of(this.afs.doc<Collection(`collections/${id}`).delete())
      .map(() =>  new actions.Success())
      .catch(err => of(new actions.Fail(err.message))
  });

See the docs on mergeMap and this helpful answer on SO about it. The stream that may throw an error is the internal of(this.afs.doc...) observable, so the .catch should be on that observable. In the current implementation (from your example above), it will always map the result of of(this.afs.doc...) to a new actions.Success(), whether it fails or not.

Upvotes: 2

Related Questions