31 lines
971 B
TypeScript
31 lines
971 B
TypeScript
import { Injectable } from '@angular/core';
|
|
import {
|
|
HttpRequest,
|
|
HttpHandler,
|
|
HttpEvent,
|
|
HttpInterceptor,
|
|
HttpErrorResponse
|
|
} from '@angular/common/http';
|
|
import { Observable, throwError } from 'rxjs';
|
|
import { Router } from '@angular/router';
|
|
import { MessageService } from './message.service';
|
|
import { catchError } from 'rxjs/operators';
|
|
|
|
@Injectable()
|
|
export class ErrorHandlerInterceptor implements HttpInterceptor {
|
|
|
|
constructor(private messageService: MessageService, private router: Router) {}
|
|
|
|
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
|
|
return next.handle(request).pipe(
|
|
catchError((errorResponse: HttpErrorResponse) => {
|
|
this.messageService.add(`Intercepted http error: ${JSON.stringify(errorResponse, undefined, 4)}`)
|
|
if (errorResponse.status === 401) {
|
|
this.router.navigate(['login'])
|
|
}
|
|
return throwError(errorResponse)
|
|
})
|
|
)
|
|
}
|
|
}
|