Move error handler to error interceptor.
This commit is contained in:
@@ -6,26 +6,51 @@ import {
|
||||
HttpInterceptor, HttpErrorResponse
|
||||
} from '@angular/common/http';
|
||||
import {Observable, throwError} from 'rxjs';
|
||||
import {catchError} from 'rxjs/operators';
|
||||
import {ErrorDialogService} from '@app/_services';
|
||||
import {catchError, retry} from 'rxjs/operators';
|
||||
import {ErrorDialogService, LoggingService} from '@app/_services';
|
||||
import {Router} from '@angular/router';
|
||||
|
||||
@Injectable()
|
||||
export class ErrorInterceptor implements HttpInterceptor {
|
||||
|
||||
constructor(private errorDialogService: ErrorDialogService) {}
|
||||
constructor(
|
||||
private errorDialogService: ErrorDialogService,
|
||||
private loggingService: LoggingService,
|
||||
private router: Router
|
||||
) {}
|
||||
|
||||
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
|
||||
return next.handle(request).pipe(catchError((err: HttpErrorResponse) => {
|
||||
if (isDevMode()) {
|
||||
this.errorDialogService.openDialog({
|
||||
message: err.error.message || err.statusText || 'Unknown Error',
|
||||
status: err.status || 0
|
||||
});
|
||||
}
|
||||
if ([401, 403].indexOf(err.status) !== -1) {
|
||||
location.reload(true);
|
||||
}
|
||||
return throwError(err);
|
||||
}));
|
||||
return next.handle(request).pipe(
|
||||
retry(1),
|
||||
catchError((err: HttpErrorResponse) => {
|
||||
let errorMessage;
|
||||
if (err.error instanceof ErrorEvent) {
|
||||
// A client-side or network error occurred. Handle it accordingly.
|
||||
errorMessage = `An error occurred: ${err.error.message}`;
|
||||
this.loggingService.sendErrorLevelMessage(errorMessage, this, {error: err});
|
||||
} else {
|
||||
// The backend returned an unsuccessful response code.
|
||||
// The response body may contain clues as to what went wrong.
|
||||
errorMessage = `Backend returned code ${err.status}, body was: ${JSON.stringify(err.error)}`;
|
||||
this.loggingService.sendErrorLevelMessage(errorMessage, this, {error: err});
|
||||
}
|
||||
if (isDevMode()) {
|
||||
this.errorDialogService.openDialog({
|
||||
message: errorMessage || err.error.message || err.statusText || 'Unknown Error',
|
||||
status: err.status || 0
|
||||
});
|
||||
}
|
||||
switch (err.status) {
|
||||
case 401: // unauthorized
|
||||
this.router.navigateByUrl('/auth').then();
|
||||
break;
|
||||
case 403: // forbidden
|
||||
location.reload(true);
|
||||
break;
|
||||
}
|
||||
// Return an observable with a user-facing error message.
|
||||
return throwError(err);
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user