Search code examples
angulartypescriptangular-http-interceptors

How to redirect to to another page on http error?


I have the following code inside a class that derives from Angular HttpInterceptor:

handleError(error: unknown): Promise<boolean> {
        if (error instanceof HttpErrorResponse) {
            return this.router.navigate([NOT_FOUND_URL, this.errorDescriptionProvider.getHttpErrorDescription(error)]);           
        }
        else
            return this.router.navigate([NOT_FOUND_URL, this.errorDescriptionProvider.getUnspecifiedNetworkErrorDescription()])
    }

and the

intercept(req: HttpRequest<T>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    const stream =  next
        .handle(req)
        .pipe
        (
           catchError(x => from(this.handleError(x)))              
        );

        //Error that boils down to: is not assignable to Observable<HttpEvent<unknow>> since its type is Observable<boolean |....>
        return  stream;
}

How to achieve the redirecting on http error?


Solution

  • Here is an example of every unorthorized requests will redirect to Login page

    import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
    import { Injectable } from "@angular/core";
    import { Observable } from "rxjs/Rx";
    import { Router } from "@angular/router";
    import { tap } from "rxjs/internal/operators";
    
    
    @Injectable()
    export class UnAuthorizedInterceptor implements HttpInterceptor {
      constructor(private router: Router) { }
      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(tap(() => { },
          (err: any) => {
            if (err instanceof HttpErrorResponse) {
              if ((err.status === 401) || (err.status === 403)) {
                this.router.navigate(['/login']);
              } else {
                return;
              }
            }
          }));
      }
    }
    

    And add { provide: HTTP_INTERCEPTORS, useClass: UnAuthorizedInterceptor, multi: true } as a provider in app.module.ts file