2016-07-18 44 views
1

我已經搜索了很多,並沒有發現任何幫助我克服駝峯的東西。我認爲我已經根據需要實現了Angular2 ExceptionHandler,但它永遠不會被調用。Angular2 ExceptionHandler無法正常工作

Main.ts:

import { bootstrap } from '@angular/platform-browser-dynamic'; 
import { disableDeprecatedForms, provideForms } from '@angular/forms'; 
import { AppComponent } from './app.component'; 
import { ExceptionHandler, Injector , provide, Provider} from '@angular/core'; 
import { APP_ROUTER_PROVIDERS } from './app.routes'; // <-- load in global routes and bootstrap them 
import { ErrorHandler } from './errorhandler/error-handler.component'; 

bootstrap(AppComponent,[ 
    APP_ROUTER_PROVIDERS, 
    disableDeprecatedForms(), 
    provideForms(), 
    provide(ExceptionHandler, {useClass: ErrorHandler}) 
]) 

錯誤handler.component.ts:

import { Component, Injectable, ExceptionHandler } from '@angular/core'; 
import { ROUTER_DIRECTIVES } from '@angular/router'; 
import { APP_PROVIDERS } from '../app.providers'; 

@Component({ 
    moduleId: module.id, 
    template: `Error happened here!!!!`, 
    directives: [ ROUTER_DIRECTIVES ], 
    providers: [ APP_PROVIDERS ] 
}) 

@Injectable() 
export class ErrorHandler extends ExceptionHandler { 

    call (exception: any, stackTrace?: any, reason?: string): void { 


    } 

} 

我有我迫使我的服務之一發生(測試HTTP錯誤異常處理),並期望我的「全局」處理程序被調用。我錯過了什麼嗎?不幸的是,現在還沒有很多文件...

TIA。

詹姆斯

回答

3

沒有如果是這樣的問題,但不要使用Component作爲一個錯誤處理程序的想法。這不是做這件事的方法。

你只需要(甚至不必要,但看起來更酷)實現接口,而不是擴展它。無需@Injectable()(但...也許這個處理器將依賴於未來,那麼它是必要的)

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

你可以讓你的引導方式是