【问题标题】:HttpInterceptor catchError does not catch - Angular 7HttpInterceptor catchError 没有捕获 - Angular 7
【发布时间】:2019-06-21 02:18:33
【问题描述】:

我正在尝试使用拦截器处理 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);
    }));
}
}

【问题讨论】:

  • 你添加到模块提供者列表了吗?
  • 我明白了,您已添加到提供者中
  • 你能试试这个吗 .pipe(tap((response: any) => { console.log(response); return response; }))
  • 检查您是否能够捕捉到响应。
  • @RakeshMakluri 是的,我可以捕捉到响应,但不能捕捉到错误发生的地方

标签: javascript angular


【解决方案1】:

这样尝试一次,希望对你有用。

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

【讨论】:

    猜你喜欢
    • 2020-09-29
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 2020-01-26
    • 1970-01-01
    • 2019-09-19
    相关资源
    最近更新 更多