Search code examples
angularerror-handlingngrxngrx-effects

Is it okay not to catchError in ngrx effect


Let's assume that I have a following code:

  fetchData$ = createEffect(() => {
    return this.actions$.pipe(
      ofType(fetchData),
      switchMap(() =>
        this.repository.fetchData().pipe(
          map(data => fetchDataSuccess({ data })),
          catchError(error => of(fetchDataFail({ error })))
        )
      )
    );
  });

In the system I've built, there is a custom handler bind to every http call, witch handles error. In a nutshell, it looks like this:

  fetchData() {
    return this.httpClient.get(`https://api.com/getData`).pipe(this.handleError());
  }

  handleError(err: HttpErrorResponse) {
    return pipe(
      catchError(err => {
        this.notification.create('Oops something went wrong');
        throw err;
      })
    );
  }

Every time when http error occurs, there is a notification created and error is printed to the console (then read by a tool for error reporting). My question is: can I safely omit catchError in effect, if I'm not doing anything with this action there, besides actually dispatching it? Error is handled somewhere else, notification is displayed to the user, this action is not handled in reducer. If I remove this, won't this cause any performance / memory issues? I understand that this will cause error to be basically thrown and not be caught anywhere
In the result effect will look like this:

  fetchData$ = createEffect(() => {
    return this.actions$.pipe(
      ofType(fetchData),
      switchMap(() =>
        this.repository.fetchData().pipe(
          map(data => fetchDataSuccess({ data }))
        )
      )
    );
  });

I've tried looking for some articles about it, but none of them mentioned this kind of situation. When I changed the effect it works perfectly well.


Solution

  • In previous versions of NgRx this WAS a problem. If an error was thrown in the effect, than the effect would unsubscribe.

    Currently the answer is yes and no. The effect has a built-in error handler, but only for the first 10 errors. You can extend this if you want by creating your own error handler.

       {
              provide: EFFECTS_ERROR_HANDLER,
              useValue: defaultEffectsErrorHandler,
            },
    

    https://github.com/ngrx/platform/blob/master/modules/effects/src/effects_error_handler.ts