捕获Angular 2异常

4
如果Angular 2遇到内部异常,它不会被记录到控制台中。如何检测以下异常?
EXCEPTION: Error during instantiation of MainFormComponent!.
ORIGINAL EXCEPTION: TypeError: Cannot set property 'crashMeMaybe' of undefined
ORIGINAL STACKTRACE:
... stacktrace ...
ERROR CONTEXT:
... context object ...

有可用的订阅服务吗?这些文档在哪里可以找到?


你尝试过使用 try...catch 吗? - Eric Martinez
我想要一个通用的解决方案来处理像window.onerror或console.error,或者node的process.on('uncaughtException')这样的错误,对于那些不能被捕获的错误。现在Angular2只是“吞噬”这样的异常,但我希望以某种方式检测它们。 - Gábor Imre
1
那么 Promise 中的 catch() 呢?我个人使用 System.import("app").catch(console.log.bind(console));,其中 import() 返回一个 Promise。 - Eric Martinez
好的概念,我可能会使用它,但仍然没有解决最初的问题:检测Angular2内部是否有东西出了问题。 - Gábor Imre
1
默认的错误处理程序使用console.log。然而,似乎在承诺方面存在一个问题,这不能通过angular2代码库来解决。 - Jesse Good
1个回答

8

有一个接口ExceptionHandler,通过它可以提供自定义实现。请参见这里文档

从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
    })
]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接