尝试扩展angular 2 exceptionHandler类时没有提供程序异常

时间:2016-07-27 13:49:19

标签: javascript exception angular error-handling angular2-services

我创建了一个扩展Angular 2中的ExceptionHandler的类。我引导它:

bootstrap(App, [
  APP_ROUTER_PROVIDERS,
  HTTP_PROVIDERS,
  provide(ExceptionHandler, { useClass: CustomExceptionHandler }),

这很好用,当我尝试注入我的API服务时会出现问题。我试过这个:

@Injectable()
export class CustomExceptionHandler extends ExceptionHandler {

  constructor( _exceptionApiService: ExceptionApiService) {
    super(new ArrayLogger(_exceptionApiService), true);
  }

  call(error, stackTrace = null, reason = null) {
    super.call(error, stackTrace, reason);
  }
}

然后是我的ArrayLogger类:

export class ArrayLogger {

  private _exceptionApiService: ExceptionApiService;

  constructor(_exceptionApiService: ExceptionApiService) {
    this._exceptionApiService = _exceptionApiService;
  }

  res = [];
  log(s: any): void { this.res.push(s); }
  logError(s: any): void { this.res.push(s); }
  logGroup(s: any): void { this.res.push(s); }
  logGroupEnd() {

    let error: Error;

    let message = this.res[0].replace('EXCEPTION: ', '');
    let stack = [];
    let index = this.findStackTrace(this.res);

    if (index === -1) {
      stack.push('Could not find stackTrace!');
    } else {
      this.res[index].split('\n').map(line => stack.push(line.trim()));
    }

    error = new Error({
      url: window.location.href,
      error: message,
      stack: stack,
      browser: this.getBrowser(navigator.userAgent),
      userAgent: navigator.userAgent,
      platform: navigator.platform,
      datetime: ''
    });

    this._exceptionApiService.post(error);

  }

  (...)

}

这给了我错误:

zone.min.js:1 Unhandled Promise rejection: (SystemJS) EXCEPTION: Error during instantiation of ApplicationRef_! (ApplicationRef -> ApplicationRef_).
    ORIGINAL EXCEPTION: No provider for ExceptionApiService! (ExceptionHandler -> ExceptionApiService)
    ORIGINAL STACKTRACE:
    Error: DI Exception
        at NoProviderError.BaseException [as constructor] (http://localhost:4200/vendor/@angular/core/src/facade/exceptions.js:27:23)
        at NoProviderError.AbstractProviderError [as constructor] 

如何正确注入exceptionAPIService?

1 个答案:

答案 0 :(得分:1)

由于您在ExceptionApiService中注入了CustomExceptionHandler,因此您也需要提供它:

bootstrap(App, [
  APP_ROUTER_PROVIDERS,
  HTTP_PROVIDERS,
  ExceptionApiService,
  provide(ExceptionHandler, { useClass: CustomExceptionHandler }),