捕获 Angular 2 个异常

Catch Angular 2 exceptions

如果Angular 2 遇到内部异常,将不会记录到控制台。

如何检测像下面这样的异常?

EXCEPTION: Error during instantiation of MainFormComponent!.
ORIGINAL EXCEPTION: TypeError: Cannot set property 'crashMeMaybe' of undefined
ORIGINAL STACKTRACE:
... stacktrace ...
ERROR CONTEXT:
... context object ...

有可用的订阅吗?这样的文档在哪里?

有一个 ExceptionHandler 接口,您可以通过它提供您选择的自定义实现。参见 and documentation

来自 BETA.0 来源:(facade/exception_handler.d.ts)

/**
 * Provides a hook for centralized exception handling.
 *
 * The default implementation of `ExceptionHandler` prints error messages to the `Console`. To
 * intercept error handling,
 * write a custom exception handler that replaces this default as appropriate for your app.
 *
 * ### Example
 *
 * ```javascript
 *
 * class MyExceptionHandler implements ExceptionHandler {
 *   call(error, stackTrace = null, reason = null) {
 *     // do something with the exception
 *   }
 * }
 *
 * bootstrap(MyApp, [provide(ExceptionHandler, {useClass:    MyExceptionHandler})])
 *
 * ```
 */

更新:

我在使用 BETA.0 时遇到了一点问题

  • 导入必须被破解,
  • 界面似乎被内部细节污染了。

我运行喜欢:

import {ExceptionHandler} from 'angular2/src/facade/exception_handler';

export interface IExceptionHandler {
    call(exception: any, stackTrace?: any, reason?: string): void;
}

export class CustomExceptionHandler implements IExceptionHandler {
    call(exception: any, stackTrace: any, reason: string): void {
        alert(exception);
    }
}

bootstrap(DemoApp, [
    new Provider(ExceptionHandler, {
        useClass: CustomExceptionHandler
    })
]);