angular - 提供者和服务中的全局错误处理程序
问题描述
我在 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
这复制了在错误时脱钩的事件。它不会复制未处理错误的全局事件处理程序......
解决方案
推荐阅读
- javascript - CREATEJS:如何检查精灵对象当前是否在屏幕上可见/渲染?
- c# - 如何将列表中的值传递给方法?消息中心?
- php - 如何在 php 中使用 JSON 数据?
- amazon-cloudformation - 在 CloudFormation 中跨不同区域添加 VPC 对等互连
- javascript - 如何从全局范围中切断功能
- r - 从指定行和列的 facet_grid 中删除未使用的因子
- google-chrome - Chrome、Firefox 中的 MDBootstrap (jQuery) 下拉菜单存在问题
- git - 从本地存储库推送后自动 git pull
- python - 处理 tkinter 框架中的视觉溢出?
- jodatime - 新的 DateTime 更改时间