user1288411
user1288411

Reputation: 149

handle errors gracefully with ngrx efffects

I have a scenario, where in when a http port error occurs, the effects gets unsubscribed, and doesn't work anymore. For Example,

@Effect() newMessages$ : Observable<any> = this.actions$
.ofType(SEND_NEW_MESSAGE_ACTION)
.switchMap(action => this.threadsService.saveNewMessage(action.payload))
.catch(() => Observable.of(new ErrorOccurredAction("Error Ocurred while saving 
message")) );

lets say error occurs, and it gets displayed in in the UI in the messages section. However after that, the send new message (post) button doesn't do another post, as the effect is no longer subscribed. Any idea how to handle this gracefully?

Upvotes: 2

Views: 302

Answers (1)

Olaf Horstmann
Olaf Horstmann

Reputation: 16882

There are basically two ways (probably more) what you could do:

1. Handle the error inside the switchMap:

@Effect() newMessages$ = this.actions$
    .ofType(SEND_NEW_MESSAGE_ACTION)
    .switchMap(action => this.threadsService.saveNewMessage(action.payload)
        .catch(() => Observable.of(new ErrorOccurredAction("Error Ocurred while saving message")))
    );

Meaning, that if there is an error in saveNewMessage, it will not affect the effect, just the single run of saveNewMessage.


2. Re-subscribe the original observable (see the catch-documentation)

@Effect() newMessages$ = this.actions$
    .ofType(SEND_NEW_MESSAGE_ACTION)
    .switchMap(action => this.threadsService.saveNewMessage(action.payload))
    .catch((err, orig) => orig.startWith(new ErrorOccurredAction("Error Ocurred while saving message")));

What the catch here does, it will return the original stream(basically a clean version of newMessages$) for the old subscription to switch the subscription to and initially emits the ErrorOccurredAction.

Both solutions are technically valid solutions, personally I prefer the first one, because it seems to be more intuitive to read for someone who it not super-familiar with the rxjs-api. (But that's just my personal taste)

Upvotes: 2

Related Questions