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.
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.
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.
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).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With