Source : https://gist.github.com/tobbbe/08e01db92c32346b226333a3f952df22
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(this.addToken(request))
.pipe(
catchError((error, ca) => {
if (error instanceof HttpErrorResponse) {
switch ((<HttpErrorResponse>error).status) {
case 401:
return this.handle401Error(request, next)
default:
return ErrorObservable.create(error);
}
} else {
return ErrorObservable.create(error);
}
})
)
}
// Method for 401 Error
handle401Error(req: HttpRequest<any>, next: HttpHandler) {
if (this.isRefreshingToken) {
this.isRefreshingToken = false;
// Reset here so that the following requests wait until the token
// comes back from the refreshToken call.
this.tokenSubject.next(null);
const http = this.inj.get(HttpClient);
let customReq: any;
let client_secret= 'temp';
let basicheader = btoa(client_secret);
return http.get(AppUtils.REFRESH_TOKEN + localStorage.getItem(AppUtils.STORAGE_ACCOUNT_REFRESH_TOKEN), { new HttpHeaders().set('Authorization', 'Basic ' + basicheader)}) // line 38
.pipe(
switchMap((token: any) => {
console.log("token " +JSON.stringify(token));
if (token) {
localStorage.setItem(AppUtils.STORAGE_TOKEN, token["access_token"]);
this.tokenSubject.next(token["access_token"]);
return next.handle(this.addToken(req));
}
console.log("refresh failed");
// If we don't get a new token, we are in trouble so logout.
this.logoutUser();
return EmptyObservable.create();
}, err => {
console.log("error calling add category" + JSON.stringify(err));
return EmptyObservable.create();
}),
catchError(error => {
console.log("error 2" +error);
// If there is an exception calling 'refreshToken', bad news so logout.
this.logoutUser();
return EmptyObservable.create();
}),
finalize(() => {
this.isRefreshingToken = true;
})
)
} else {
return this.tokenSubject
.filter(token => token != null)
.take(1)
.switchMap(token => {
return next.handle(this.addToken(req));
});
}
}
The above code snippet is used to handle the refresh token, reference
If encountering issues like when the line 38 refresh call is successful, the functionality works fine. However, when receiving a 401 error response, the control is not going to the catchError or error block as expected. During debugging, it's difficult to determine where the control goes after failure.
Any insights on what might be going wrong with this implementation? How can one ensure that the control ends up in the error block after receiving a 401 error response? This code is implemented in Angular 5.
You can find the complete code for the request interceptor https://plnkr.co/edit/7ASmr - please note that this is not the working version, just the code snippet.