Skip to content

Commit 4e0815f

Browse files
committed
fix error messaging
1 parent 0a61301 commit 4e0815f

File tree

1 file changed

+22
-14
lines changed

1 file changed

+22
-14
lines changed
Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import { catchError } from 'rxjs/operators';
1+
import { catchError, tap } from 'rxjs/operators';
22
import { Injectable } from '@angular/core';
3-
import { OAuthService, OAuthStorage } from 'angular-oauth2-oidc';
3+
import { OAuthService } from 'angular-oauth2-oidc';
44
import { Observable, throwError } from 'rxjs';
55
import {
66
HttpErrorResponse,
@@ -16,42 +16,50 @@ export class OAuthInterceptor implements HttpInterceptor {
1616
excludedUrls = ['assets', '/assets'];
1717
excludedUrlsRegEx = this.excludedUrls.map((url) => new RegExp('^' + url, 'i'));
1818

19-
constructor(
20-
private oauthService: OAuthService,
21-
private authStorage: OAuthStorage,
22-
private snackbar: SnackbarService
23-
) {}
19+
constructor(private oauthService: OAuthService, private snackbar: SnackbarService) {}
2420

2521
private isExcluded(req: HttpRequest<any>): boolean {
2622
return this.excludedUrlsRegEx.some((toBeExcluded) => toBeExcluded.test(req.url));
2723
}
24+
2825
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
2926
if (this.isExcluded(req)) {
3027
return next.handle(req);
3128
}
32-
const token = this.authStorage.getItem('access_token');
33-
const headers = req.headers.set('Authorization', 'Bearer ' + token);
34-
req = req.clone({ headers });
29+
const token = this.getToken();
30+
if (token) {
31+
const headers = req.headers.set('Authorization', 'Bearer ' + token);
32+
req = req.clone({ headers });
33+
}
3534
return next.handle(req).pipe(
3635
catchError((error: HttpErrorResponse) => {
36+
console.error('OAuthInterceptor: Error occurred', error);
3737
if (error.status === 401) {
3838
this.oauthService.logOut();
3939
}
4040
if (error.status === 404) {
4141
this.handleErrorCodes(error.status);
4242
}
43-
if (error.error.issue) {
43+
if (error.error?.issue) {
4444
this.handleErrorCodes(error.error.issue[0]?.code);
4545
}
46-
if (error.error.issues) {
47-
this.handleErrorCodes(error.error.issues[0]?.code, error.headers.get('Retry-After'));
46+
if (error.error?.issues) {
47+
const retryAfter = error.headers.get('Retry-After');
48+
this.handleErrorCodes(error.error.issues[0]?.code, Number(retryAfter));
4849
}
4950
return throwError(error);
5051
})
5152
);
5253
}
5354

54-
public handleErrorCodes(errorCode, retryAfter?) {
55+
private getToken(): string | null {
56+
if (this.oauthService.hasValidAccessToken()) {
57+
return this.oauthService.getAccessToken();
58+
}
59+
return null;
60+
}
61+
62+
public handleErrorCodes(errorCode, retryAfter?: number) {
5563
this.snackbar.displayErrorMessage(errorCode, retryAfter);
5664
}
5765
}

0 commit comments

Comments
 (0)