简体   繁体   中英

Angular2 rxjs - switchmap catch error

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);
    }
  }

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([]);
    })
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM