platform icon indicating copy to clipboard operation
platform copied to clipboard

Effect stops working after an exception occurs

Open tlaak opened this issue 8 years ago • 31 comments

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[x] Bug report  
[ ] Feature request
[ ] Documentation issue or request

What is the current behavior?

An effect stops working when an exception occurs, i.e. the effect only runs once and further dispatched actions don't trigger the effect anymore.

Example: User loads a page and a GET_STUFF action is dispatched, but the login has expired causing a 401 response from the API endpoint. An error observable is returned from the effect and user is redirected to the login page. User logs in and navigates back to the previous page, GET_STUFF is dispatched again, but this time the effect doesn't run and no API call is made.

Recovering from this needs a full page reload.

Expected behavior:

The effect should always run when a matching action is dispatched.

Minimal reproduction of the problem with instructions:

Here's the code that I have in my effect (imports excluded).

@Injectable()
export class StuffEffects {
  constructor(
    private actions$: Actions,
    private dataService: DataService
  ) {}

  private getStuff(): Observable<Action> {
    return this.dataService.getStuff().pipe(
      map((data: Stuff[]) => {
        return { type: GET_STUFF_SUCCESS, payload: data };
      }),
      catchError(error =>
        ErrorObservable.create({
          type: GET_STUFF_FAILED,
          payload: error,
        })
      )
    );
  }

  @Effect()
  getStuff$: Observable<Action> = this.actions$
    .ofType(GET_STUFF)
    .pipe(
      switchMap(() => this.getStuff())
    );
}

Code for the dataService.getStuff is simply returning the response from the request:

  getStuff(): Observable<any> {
    return this.http.get('//server.example.org/apiEndpoint');
  }

I have an interceptor adding authorisation headers in the call.

Version of affected browser(s),operating system(s), npm, node and ngrx:

Node 8.9.0, npm 5.5.1, ngrx 4.1.1, rxjs 5.5.5, Angular 5.1

Other information:

There are similar issues in the version 2 of the library, e.g. https://github.com/ngrx/effects/issues/89 and https://github.com/ngrx/effects/issues/155

tlaak avatar Dec 14 '17 09:12 tlaak

This is not a bug, but how RxJS works. You catch the error in the inner observable and return a new non-error observable to keep the outer stream from "dying".

brandonroberts avatar Dec 14 '17 14:12 brandonroberts

Confirmed: Returning of({ ... }) from the catchError block works so TIL.

tlaak avatar Dec 14 '17 14:12 tlaak

See also https://github.com/ngrx/effects/issues/158

bbaia avatar Dec 14 '17 15:12 bbaia

Thank you guys! I also struggled with this.

Brandinga avatar Dec 14 '17 16:12 Brandinga

I'll add a section on error handling to the docs since this is a reoccurring thing that people trip up on

brandonroberts avatar Dec 14 '17 17:12 brandonroberts

During my presentation I specifically highlight this in the Gotchas section. Yeah, it has nothing to do with @Effects but instead this is how Observables work.

alex-okrushko avatar Dec 14 '17 17:12 alex-okrushko

Does this mean it's not possible to use Angular's global error handling with Effects?

I have submitted a question on SO regarding this.

I currently make use of it to throw errors and route them to the correct places:

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  private messagesService: MessagesService
  private router: Router

  constructor(
    private injector: Injector, // DI workaround (https://stackoverflow.com/a/41585902)
    private errorLoggerService: ErrorLoggerService
  ) {
    // DI workaround (https://stackoverflow.com/a/41585902)
    setTimeout(() => (this.messagesService = injector.get(MessagesService)))
    setTimeout(() => (this.router = injector.get(Router)))
  }

  handleError(error) {
    if (error instanceof HttpErrorResponse) {
      this.handleServerError(error)
    } else if (error instanceof ClientError) {
      this.handleClientError(error)
    } else {
      this.handleUnexpectedError(error)
    }
  }

akrueger avatar Jan 02 '18 16:01 akrueger

Hi, I believe i am catching the error properly, but after the first error the effect stops working.

@Effect()
    startAd: Observable<Action> = this.actions$
        .ofType(AdvertActions.START_AD)
        .pipe(
            tap(action => console.log(action)),
            map(action => action.payload),
            switchMap(campaign => this.advertService.startAd(campaign.name)),
            map(nameOfUploadedFile => new AdvertActions.StartAdDone(nameOfUploadedFile)),
            catchError(err => of(new AdvertActions.StartAdFailed(err))),
        );

Any idea what else could cause this?

imohiosen avatar Apr 15 '18 20:04 imohiosen

Hey @imohiosen. You should be handling errors inside the switchMap. That way the stream continues after an error occurs.

@Effect()
    startAd: Observable<Action> = this.actions$
        .ofType(AdvertActions.START_AD)
        .pipe(
            tap(action => console.log(action)),
            map(action => action.payload),
            switchMap(campaign => 
              this.advertService.startAd(campaign.name).pipe(
                map(nameOfUploadedFile => new AdvertActions.StartAdDone(nameOfUploadedFile)),
                catchError(err => of(new AdvertActions.StartAdFailed(err))
             )
          )
        );

brandonroberts avatar Apr 15 '18 21:04 brandonroberts

Thanks @brandonroberts. That fixed it.

imohiosen avatar Apr 15 '18 22:04 imohiosen

Off-topic @imohiosen Also consider using concatMap instead of switchMap as a first choice. https://blog.angularindepth.com/switchmap-bugs-b6de69155524

alex-okrushko avatar Apr 23 '18 13:04 alex-okrushko

@imohiosen and @brandonroberts here is another solution to do error handling at the end ot the pipe operators (stream global Effect error handler 👍 ) : instead of write:

    catchError(() => { return of(obj); })

we should write:

    catchError(err,caught)=>{ 
     // do something here; i.e. send some err message to store with store.dispatch(...)
      return caught; //return the caught observable to retry.
     } 

@imohiosen 's example could be written as:

    @Effect()
    startAd: Observable<Action> = this.actions$
        .ofType(AdvertActions.START_AD)
        .pipe(
            tap(action => console.log(action)),
            map(action => action.payload),
            switchMap(campaign => this.advertService.startAd(campaign.name)),
            map(nameOfUploadedFile => new AdvertActions.StartAdDone(nameOfUploadedFile)),
            catchError((err,caught) => {
               this.store.dispatch(new AdvertActions.StartAdFailed(err)); 
               return caught;
            })
        );

Explanation:

CatchError operator allows to handle error, but doesn't change nature of observable - error is terminal condition to given observable so emission will stop. CatchError allows to emit desires value when it occurs instead of raising observer's error callback. catchError

In here, catch is handled in main stream, so error raised in inner observable (in switchmap) bubbles up to main stream, substituted into handled value, then completes (stops). the catchError operator also provide a second parameter to retry the source observable, above is this solution used as a global stream error handler. You could also handle error in inner observable like 'switchmap(x => x.catch())' (solution of @brandonroberts )then error raised in innerobervable will not bubble up, so won't stop main observable.

Conlution:

  • you should always add a catchError operator as a global Effect error handler to prevent the Effect stop!

metasong avatar Jun 20 '18 06:06 metasong

https://medium.com/city-pantry/handling-errors-in-ngrx-effects-a95d918490d9

ghost avatar Jul 05 '18 10:07 ghost

@brandonroberts you saved my ass thanks!

ghaithAqidi avatar Jan 17 '19 12:01 ghaithAqidi

@metasong

Yours is the solution I was looking for. Continually having to go inside each switchMap to catch errors brings back the often despised callback hell that people have spent significant effort to avoid. Not sure why people have deemed it acceptable when it comes to rxjs (or is it ngrx? I'm new to observables in general, so please take it easy on me!).

Anyway, thanks for your solution! It is rather annoying that we can't just return actions from the final catchError, but I understand that's not the current API.

akmjenkins avatar Mar 01 '19 16:03 akmjenkins

Is there a reason or preference for using @metasong vs @brandonroberts solution to catching errors? These both work and appear equally valid, but I'm not intimately familiar with inner workings, so should we be using one over the other?

dcanning avatar Jul 12 '19 16:07 dcanning

@brandonroberts solution is preferred (handle before flattening). If error stays unhandled then a variation of @metasong solution would be automatically applied (https://ngrx.io/guide/effects/lifecycle#resubscribe-on-error)

alex-okrushko avatar Jul 15 '19 12:07 alex-okrushko

@alex-okrushko are those versions tied to @angular/core version, or can ngrx 8 be used with angular 6?

dcanning avatar Aug 29 '19 16:08 dcanning

@dcanning My understanding is that NgRx 8 would have to be used with angular 8+.

alex-okrushko avatar Aug 30 '19 13:08 alex-okrushko

@brandonroberts it really works, thank you soo much.

redwolfgang24 avatar Sep 13 '19 12:09 redwolfgang24