角度4的全局错误处理程序

时间:2018-03-06 11:58:07

标签: javascript angular typescript

I want to capture this err. And need to extract component name in that URL. How can I capture zone.js error?? and trace it into the component?

这是我附加了我的代码。我已经实现了全局处理程序,现在我需要从zone.js上的 500错误中提取“仪表板”。我怎样才能在全局处理程序中获取它。有什么方法可以得到我想要的输出吗?

import { ErrorHandler, Injectable, Injector, NgZone } from '@angular/core';
import { LocationStrategy, PathLocationStrategy } from '@angular/common';
import { LogService } from './logging-service.service';
import * as StackTrace from 'stacktrace-js';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  private errors = new Array<any>();
  constructor(public injector: Injector, public zone: NgZone) {
  }
  public handleError(error: any) {
    console.log('Im a global handler', JSON.parse(error));
    const logService = this.injector.get(LogService);
    const location = this.injector.get(LocationStrategy);
    const message = error.message ? error.message : error.toString();
    const url = location instanceof PathLocationStrategy
      ? location.path() : '';
    const callbackFun = function (stackframes) {
      const stringifiedStack = stackframes.map(function (sf) {
        return sf.toString();
      }).join('\n');
      console.log(stringifiedStack);
    };


    const errback = function (err) {
      console.log(err);
      console.log(err.stack);
    };
    window.onerror = function (msg, file, line, col, error) {
      // this.zone.fromError.subscribe(this.onZoneError);
      StackTrace.fromError(message).then(callbackFun).catch(errback);
      StackTrace.get().then(callbackFun).catch(message);
    };
    const handleErrorData = {
      // Some Json to send to server
    };
    logService.logError(handleErrorData);
    throw error;
  }
  public onZoneError(error) {
    console.log(error);
    console.error('Error', error instanceof Error ? error.message : error.toString());
  }

}

1 个答案:

答案 0 :(得分:4)

实施HttpInterceptor(需要Angular 4.3.x)

从那里听取错误并提取请求网址并将其拆分为部分。