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

Nan*_*ani 7 angular-http-interceptors angular angular-httpclient

我有一个全局的HttpInterceptor,带有一个处理HttpErrorResponse的catch块。但是我的要求是,当服务进行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>>();
    }
  );
 }
}
Run Code Online (Sandbox Code Playgroud)

和服务电话:

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')
     );
}
Run Code Online (Sandbox Code Playgroud)

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

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

Yer*_*kon 3

解决的一种方法是通过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);
      })
  }
Run Code Online (Sandbox Code Playgroud)

拦截器.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);
        }

      }
    );
  }
Run Code Online (Sandbox Code Playgroud)

并检查 的interceptor错误回调中的请求标头。但在此解决方案中,任何地方拦截器都会在任何服务调用之前处理请求。

StackBlitz 示例