从子组件捕获错误。自定义ErrorHandler。不单身

时间:2018-09-07 23:11:16

标签: angular error-handling custom-error-handling angular-errorhandler

我正在将组件的内容包装到另一个组件中,这是为了控制状态,例如加载|编辑|查看等。

我想从此类包装组件的子组件中捕获错误。

  

为什么,这行不通?

我有自定义ErrorHandler

@Injectable()
export class DynamicStateErrorHandler implements ErrorHandler {
  constructor() {
    console.log('imhere');
  }
  handleError(error: any): void {
    alert(error);
  }
}

我是这样提供的:

@Component({
  selector: 'app-dynamic-state',
  templateUrl: './dynamic-state.component.html',
  styleUrls: ['./dynamic-state.component.scss'],
  providers: [
    {
      provide: ErrorHandler,
      useClass: DynamicStateErrorHandler,
      multi: true
    }
  ]
})

正如我从DI指南中了解到的那样,我的自定义ErrorHandler应该可用于app-dynamic-state的所有子级,每个DynamicStateComponent实例都可以使用

我这样测试:

...
@Component({
  selector: 'app-test-err-cmp',
  template: `
    <div></div>
  `,
})
class TestErrorComponent implements AfterViewInit {
  ngAfterViewInit() {
    throw new Error('test error');
  }
}

@Component({
  selector: 'app-test-cmp',
  template: `
    <app-dynamic-state [state]="state">
      <div class="test-content"></div>
      <ng-template *ngIf="testError" #editingTemplate>
        <app-test-err-cmp></app-test-err-cmp>
      </ng-template>
      <ng-template *ngIf="testTemplate" #viewingTemplate>
        <div class="test-viewing-template"></div>
      </ng-template>
    </app-dynamic-state>
  `,
})
class TestWrapperComponent implements OnInit {
  public testError: boolean;
  public testTemplate: boolean;
  public state: Observable<DynamicState>;
  public $state = new Subject<DynamicState>();
  ngOnInit() {
    this.state = this.$state.asObservable();
  }
}
...

it('should display internal errors', async(() => {
      hostFixture.componentInstance.testError = true;
      hostFixture.detectChanges();
      component.ngAfterContentInit();
      hostFixture.componentInstance.$state.next(ComponentDynamicStates.EDITING);
      expect(() => {
        hostFixture.detectChanges();
      }).toThrowError('test error');
      expect((<DebugElement>hostFixture.debugElement.childNodes[0]).query(By.css('app-error'))).toBeTruthy();
      expect(component.stateContext.err).toBeTruthy();
    }));

引发错误,但是从未调用过我的handleError方法。

0 个答案:

没有答案