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