首页 > 解决方案 > 提供者和服务中的全局错误处理程序

问题描述

我在 Angular 8 中有一个错误服务设置,它按照我的预期处理来自组件的所有错误 - 记录到控制台而不抛出任何其他错误。

import { Injectable, ErrorHandler } from '@angular/core'

@Injectable()
export class ErrorService implements ErrorHandler {
  constructor() { }
  handleError(error) {
    console.error('An error occurred:', error.message);
  }
}

但是在 DocumentService(提供程序中列出的任何内容)中,如果抛出错误,它偶尔会通过 ErrorService,但通常不会命中该代码。

  providers: [
    ErrorService
    , {
      provide: ErrorHandler,
      useClass: ErrorService,
    }
    , DocumentService
    ],

DocumentService 被注入到这样的组件中

export class MainComponent implements OnInit {

  @ViewChild('pdfViewer', { static: false }) public pdfViewer;
  @ViewChild('claimPdfViewer', { static: false }) public claimPdfViewer;

  selectedElements: HTMLElement[] = [];

  constructor(private documentService: DocumentService) {
...

我需要做什么才能让 DocumentService(以及提供程序中的任何其他内容)始终使用我的 ErrorService,或者是否有其他方法可以全局处理来自服务的错误?

编辑:仅当异常发生在可观察订阅或事件处理程序中时,才到达全局事件处理程序

    this.traceService.onHighlightTrace.subscribe(traces => {
      if (traces != this.documentService.searchTraces) {
        this.documentService.clearAllPagesOfAllHighlights();
        //exception gets thrown in this.clearAllPagesOfAllHighlights(); and there is 
// no try/catch in there so I would expect the exception to get caught by the handler.
        //instead exception never goes to the global error handler and just 
//gets logged to the console as uncaught
        ....

编辑 2: https ://stackblitz.com/edit/globalerror-handler

这复制了在错误时脱钩的事件。它不会复制未处理错误的全局事件处理程序......

标签: angulartypescriptangular-cliangular8angular-services

解决方案


推荐阅读