首页 > 解决方案 > Angular:拦截HTTP错误并继续链

问题描述

我想将某些 HTTP 错误代码视为非错误,并正常处理它们的响应。所以我尝试添加一个HttpInterceptor来捕获 500 个状态代码,并返回原始响应(Angular 放入error.error):

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.status === 500) {
          return of(error.error);
        } else {
          return throwError('server error');
        }
      })
    );
  }

但是,如果出现错误,我通过管道传输到我的 http 请求的任何内容都不会被执行。例如,如果我这样做,日志语句不会发生:

this.http.get(...).pipe(
  tap(console.log)
)

我怎样才能使这项工作?

这是一个示例……它从不从 AppComponent 记录“得到结果”。

标签: angularrxjs

解决方案


你的链停止工作,因为 Angular http 模块过滤了它从拦截器接收到的消息:

const res$: Observable<HttpResponse<any>> = <Observable<HttpResponse<any>>>events$.pipe(
        filter((event: HttpEvent<any>) => event instanceof HttpResponse));

如您所见,您应该返回HttpResponse类流,例如:

import { HttpResponse, ... } from '@angular/common/http';
...

if (error.status === 404) {
  console.log('caught', error.error);

  return of(new HttpResponse({
    body: error.error
  }));
}

分叉的 Stackblitz


推荐阅读