Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rxjs catchError not working when piped from angular service

Using redux and Angular, I have the following effect:

  @Effect()
  public authenticate: Observable<Action> = this.actions
    .ofType(AUTHENTICATE)
    .pipe(
      map((action: AuthenticateAction) => action.payload),
      switchMap(payload => {
        return this.userService.authenticateUser(payload.email, payload.password).pipe(
          map(auth => new AuthenticationSuccessAction({ auth: auth })),
          catchError(error => of(new HttpErrorAction({ error: error })))
        );
      })
    );

The service:

  public authenticateUser(email: string, password: string): Observable<IAuthentication> {
    const formData: FormData = new FormData();
    formData.append('email', email);
    formData.append('password', password);
    return this.httpClient.post('/api/auths/useraccounts', formData) as Observable<IAuthentication>;
  }

When the POST fails, the HttpErrorAction never gets dispatched.

like image 864
that_guy Avatar asked Jun 11 '18 15:06

that_guy


People also ask

What is catchError in RxJs?

RxJS catchError() operator is an error-handling operator used to handle and take care of catching errors on the source observable by returning a new observable or an error.

Where do you put catchError?

Always put the “catchError” operator inside a switchMap (or similar) so that it only ends the API call stream and then returns the stream to the switchMap, which continues the Observable.

How do you perform error handling in Observable in angular?

Angular CatchError is an RxJs Operator. We can use it to handle the errors thrown by the Angular Observable. Like all other RxJs operators, the CatchError also takes an observable as input and returns an observable (or throws an error).


1 Answers

Turns out I forgot I had an HttpInterceptor that I caught http errors like so:

return next.handle(authReq).pipe(catchError(
      (error) => {
        return of(error);
      }

If I wanted to bubble the error up to the effect i'd do something like:

return Observable.throw(error);

Update with newer versions of rxjs:

return throwError(error);
like image 144
that_guy Avatar answered Oct 13 '22 02:10

that_guy