我在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
这将复制由于错误而取消钩挂的事件。它不会复制未处理错误的全局事件处理程序。...