2

我想在我的自定义错误处理程序中调用我的 rest API,以便在调用处理程序时给自己发送电子邮件。

我曾尝试使用 Injector,但出现此错误:

Error: Cannot instantiate cyclic dependency! HttpClient

在这里你可以看到我的错误处理程序:

import { Router } from '@angular/router';
import { ErrorHandler, Injector, Injectable, NgZone } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class AppErrorHandler extends ErrorHandler {

  constructor(private injector: Injector) {
    super();
  }

  private get toastrService(): ToastrService {
    return this.injector.get(ToastrService);
  }

  private get http(): HttpClient {
    return this.injector.get(HttpClient);
  }

  private get router(): Router {
    return this.injector.get(Router);
  }

  private get ngZone(): NgZone {
    return this.injector.get(NgZone);
  }

  public handleError(error: any): void {
    if (error.status === 401) {
      this.ngZone.run(() => this.router.navigate(['/home']));
      this.toastrService.error('Login first', 'Error');
    } else if (error.status === 403) {
      this.ngZone.run(() => this.router.navigate(['/home']));
      this.toastrService.error('unauthorize', 'Error');
    } else {
      this.http.post<any>('/api/error-mailer', error).subscribe(() => { });
      this.toastrService.error('Something went wrong', 'Error', { onActivateTick: true });

    }

    super.handleError(error);
  }
}

我可能也有错误的方法,所以如果你能帮助我,那就太好了!

4

1 回答 1

3

您应该使用http 拦截器处理 httpClient 错误。在拦截器中,您可以注入您需要的服务。但是,您应该注意从拦截器调用 http 请求,因为它会通过拦截器运行,并且当您的错误邮件程序关闭时,您最终可能会出现循环。

于 2020-04-21T15:46:06.277 回答