简体   繁体   中英

HttpInterceptor catchError does not catch - Angular 7

I'm trying to handle HTTP errors with interceptor but catchError method does not seems to fire when error occurs (422). None of errors are intercepted by this method. Providers in app.module has added (i can read events and 200 respons).

import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpErrorResponse, HttpResponse,
} from '@angular/common/http';

import {Observable, throwError} from 'rxjs';
import {catchError} from 'rxjs/operators';

@Injectable()
export class RequestInterceptor implements HttpInterceptor {

constructor() {}

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

return next.handle(request)
  .pipe(
    catchError((error: HttpErrorResponse) => {
      console.log(error);
      return throwError(error);
    }));
}
}

try like this once, i hope this is useful to you.

@Injectable()
export class HttpXsrfInterceptor implements HttpInterceptor {
   constructor(private tokenService: HttpXsrfTokenExtractor) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): 
  Observable<HttpEvent<any>> {
    const headerName = 'X-XSRF-TOKEN';
    const token = this.tokenService.getToken() as string;
    if (token && !req.headers.has(headerName)) {
      req = req.clone({ headers: req.headers.set(headerName, token) });
    }

    return next.handle(req)
        .do(sucess => {/*todo*/}
            , err => this.handleError(err));
 }

 private handleError(err: any) {
    TODO: Handle error.
 }
}

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