简体   繁体   中英

error handling with http interceptor not working in Angular

I am working on Angular 8

I am trying to centralise error handling through Interceptor

My Interceptor code is running , but it is not returning any error

import {
    HttpEvent,
    HttpInterceptor,
    HttpHandler,
    HttpRequest,
    HttpResponse,
    HttpErrorResponse
   } from '@angular/common/http';
   import { Observable, throwError } from 'rxjs';
   import { retry, catchError } from 'rxjs/operators';
import { RestService } from './restservice';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';


@Injectable()
   export class HttpErrorInterceptor implements HttpInterceptor {

    constructor(private rest : RestService , private route : Router){}



    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      // console.log('jcsjdsjd');
      // console.error('xjxfjb');
      // console.log(request);
      // console.log(next);
      return next.handle(request).pipe(catchError(err => {
        console.log(err);
          if (err.status === 401) {
              // auto logout if 401 response returned from api
              // this.authenticationService.logout();
              location.reload(true);
          }

          const error = err.error.message || err.statusText;
          return throwError(error);
      }))
  }
} 

I have also defined interceptor in Providers of app.module.ts

  providers: [RestService  , AuthGuard ,   commonRest    ,  {
    provide: HTTP_INTERCEPTORS,
    useClass: HttpErrorInterceptor,
    multi: true
  }],

response that I am getting on request with error 403 is :

    {
  "messagecode": 403,
  "message": "not valid token!"
}

为了在全球范围内使用拦截器并且提供者在核心模块中,应该在拦截器的顶部添加 @Injectable({ providedIn: 'root' }) 像这里https://stackblitz.com/edit/angular-http-interceptor-working-for -lazy-loaded-module?file=src/app/core/token-interceptor.service.ts

Make sure your API returns JSON response in the following format,

{
   "status" : "403",
   "message" : "Session expired"
}

The following work for me, (I am having tap in the example below, in case if you want to extract something from a successful JSON response).

The errors can be handled in the catchError section. See, provided error.status examples for 403 & 401 . Feel free to customise that section.

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(request).pipe(
      tap(evt => {
        if (evt instanceof HttpResponse) {
          
        }
      }),
      catchError(err => {
        if (err.status === 403) {
          // Handle 403 specific errors
        } else if (err.status === 401) { 
          // Handle 401 specific errors
        }

        const error = err.error.message || err.statusText;
        return throwError(error);
      }), map(event => {
        if (event instanceof HttpResponse) {

        }
        return event;
      }), catchError(this.handleError));
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      // console.error(
      //   `Backend returned code ${error.status}, ` +
      //   `body was: ${error.error}`);

      // TODO :  do the logout here.
      // console.log(
      //   `Backend returned code ${error.status}, ` +
      //   `body was: ${error.error}`);
      // this.router.navigate(['/login'], { queryParams: { returnUrl: '' }});
    }
    // return an observable with a user-facing error message
    return throwError(error);

  }

I hope this helps someone.

Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM