Angular2 中的自定义异常处理程序

Custom Exception Handler in Angular2

在 angular2 中,异常默认记录在控制台中。我听说我们可以继承 Angular ExceptionHandler 并创建我们自己的异常处理程序,以便我们可以覆盖默认行为。我尝试这样做但没有成功。谁能举个例子帮我解决这个问题。提前致谢....

看来您需要创建自己的 class 来处理异常,然后在 bootstrap 时将其绑定到您的应用程序中,如下所示:

import {provide, ExceptionHandler} from '@angular/core';

class MyExceptionHandler implements ExceptionHandler {
    call(error, stackTrace = null, reason = null) {
       // do something with the exception
    }
 }

然后在 bootstrap 时,将此新实现绑定为 ExceptionHandler:

bootstrap(MyApp, 
    [provide(ExceptionHandler, {useClass: MyExceptionHandler})])

参考here

Plunker example

这是一个在 alpha .46 中工作的异常处理程序

import {ExceptionHandler} from 'angular2/angular2';

export class ERISExceptionHandler extends ExceptionHandler {

    call(error, stackTrace = null, reason = null) {
        alert('error:' + error + ' stackTrace: ' + stackTrace + ' reason: ' + reason);
    }
}

从版本 2.0.1 开始,当前创建自定义错误处理程序的方法是 @angular/core 中的 ErrorHandler 接口。

来自文档:

https://angular.io/docs/ts/latest/api/core/index/ErrorHandler-class.html

import { NgModule, ErrorHandler } from '@angular/core';

class MyErrorHandler implements ErrorHandler {
  handleError(error) {
    // do something with the exception
  }
}
@NgModule({
  providers: [{ provide: ErrorHandler, useClass: MyErrorHandler }]
})
class MyModule {}

在根模块上应用此方法时,所有子模块将收到相同的错误处理程序(除非它们在其提供者列表中指定了另一个错误处理程序)。