【问题标题】:Catch Angular 2 exceptions捕捉 Angular 2 异常
【发布时间】:2015-08-11 15:24:04
【问题描述】:

如果 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吗?
  • 我想要一个通用的解决方案来处理诸如 window.onerror 或 console.error 或 node 的 process.on('uncaughtException') 之类的错误,因为这些错误没有被捕获,或者可能无法被捕获。现在 Angular2 只是“吞下”这样的异常,但我想以某种方式检测它们。
  • 那么来自 Promises 的 catch() 呢?我个人使用System.import("app").catch(console.log.bind(console));,其中import() 返回一个Promise。
  • 好概念,我可能会使用它,但仍然没有解决最初的问题:检测 Angular2 内部是否有东西破裂。
  • 默认error handler 使用console.log。但是,似乎有一个带有承诺的issue 无法由 angular2 代码库修复。

标签: angular exception


【解决方案1】:

有接口 ExceptionHandler 通过它您可以提供您选择的自定义实现。请参阅heredocumentation

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

【讨论】:

    猜你喜欢
    • 2012-01-10
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    • 2012-03-20
    相关资源
    最近更新 更多