HttpInterceptor catchError无法捕获-Angular 7

时间:2019-01-28 05:16:23

标签: javascript angular

我正在尝试使用拦截器来处理HTTP错误,但是当发生错误时,catchError方法似乎不会触发(422)。此方法不会拦截任何错误。 app.module中的提供程序已添加(我可以读取事件和200个响应)。

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);
    }));
}
}

1 个答案:

答案 0 :(得分:0)

尝试一次,希望对您有用。

@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.
 }
}