Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 rxjs - switchmap catch error

Tags:

angular

rxjs

I'd like to be able to handle any errors that error when calling this.authService.refreshToken(). Can errors be handled within the switchmap block, or how do I go about handling an error in this case?

post3(endpoint: string, body: string) : Observable<any> {
    if (this.authService.tokenRequiresRefresh()) {
      this.authService.tokenIsBeingRefreshed.next(true);
      return this.authService.refreshToken().switchMap(
        data => {
          this.authService.refreshTokenSuccessHandler(data);
          if (this.authService.loggedIn()) {
            this.authService.tokenIsBeingRefreshed.next(false);
            return this.postInternal(endpoint, body);
          } else {
            this.authService.tokenIsBeingRefreshed.next(false);
            this.router.navigate(['/sessiontimeout']);
            Observable.throw(data);
          }
        }
      );
    }
    else {
      return this.postInternal(endpoint, body);
    }
  }
like image 918
blgrnboy Avatar asked Jan 20 '17 00:01

blgrnboy


People also ask

How do you handle errors in switchMap?

Good Error Handling 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 I get an observable error message?

Catch errors in the observable stream Another option to catch errors is to use the CatchError Operator. The CatchError Operators catches the error in the observable stream as and when the error happens. This allows us to retry the failed observable or use a replacement observable.

Which RxJS operator can be chained to an observable to handle errors?

The catchError operator takes as input an Observable that might error out, and starts emitting the values of the input Observable in its output Observable.


1 Answers

use the catchError method

this.authService.refreshToken()
  .pipe(
     switchMap(() => {...}),
     catchError((e) => {
       // handle e and return a safe value or re-throw
       if (isCritical(e)) {
         return throwError(e);
       }
       return of([]);
    })
  );
like image 166
shusson Avatar answered Sep 20 '22 12:09

shusson