Angular 5 HttpInterceptor 错误处理首先调用调用者的错误处理

标签 angular angular-http-interceptors angular-httpclient

我有一个全局 HttpInterceptor,它带有一个处理 HttpErrorResponse 的 catch block 。但我的要求是,当服务进行 http 调用并且还有错误处理程序时,我希望服务上的错误处理程序首先关闭。如果此服务上没有错误处理程序,那么我希望全局 HttpInterceptor 错误处理程序来处理它。

示例代码:

HTTP拦截器:

@Injectable()
export class ErrorHttpInterceptor implements HttpInterceptor {

constructor(private notificationService: NotificationService) {}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req)
  .catch(
    error => {
      if (error instanceof HttpErrorResponse) {
        this.notificationService.error('Error', 'Error in handling Http request');
      }

      return Observable.empty<HttpEvent<any>>();
    }
  );
 }
}

服务调用:

updateUser(id, data) {
  return this.http
    .patch(`${API.userUrl}/${id}`,  {data: data})
    .subscribe(
      () => console.log('success'),
      (err) => this.notificationService.error('custom code to handle this')
     );
}

在这种情况下,ErrorHttpInterceptor 会发出通知,然后 userService 错误处理也会发出错误通知。

但在我的用例中,我希望 ErrorHttpIntercetor 仅在底层订阅未处理错误时才处理错误。有办法做到这一点吗?

最佳答案

解决方法之一是通过请求传递httpHeaders:

 request() {  
    const url = 'GoalTree/GetById/'; 
    let headers = new HttpHeaders();
    headers = headers.append('handleError', 'onService');
    this.http.get(url, {headers: headers})
      .pipe(
      map((data: any) => {
        this.showError = false; 
      }),
      catchError(this.handleError)
      )
      .subscribe(data => {
        console.log('data', data);
      })
  }

拦截器.ts:

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

    this.spinnerService.show();

    return next.handle(req).do(
      (event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
          this.spinnerService.hide();
        }
      },
      (err: any) => {
        if (req.headers.get('handleError') === 'onService') {
          console.log('Interceptor does nothing...');
        } else {
          console.log('onInterceptor handle ', err);
        }

      }
    );
  }

并在拦截器的错误回调中检查请求 header 。 但是在这个解决方案中,拦截器在任何服务调用之前处理请求。

StackBlitz Example

关于Angular 5 HttpInterceptor 错误处理首先调用调用者的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49740933/

相关文章:

javascript - TypeScript 中的 findIndex 数组方法

angularjs - Angular http 拦截器

javascript - AngularJS:如何保持在 'run' 方法直到完成

Angular RxJS - 如何监控 HTTP Get 请求(非文件)的进度

Angular 5,HttpClient 将日期字段更改为 UTC

javascript - Angular 4 : How to include external js libraries?

jquery - 如何在 Angular 4 或 4+ 应用程序中导入 Bootstrap 4 主题

angular - IONIC 4 ionic 菜单打开关闭时出现菜单错误

angular - Http拦截器的顺序

angular - 如何将 header 添加到我的 Angular 发布请求中?