Scipion
Scipion

Reputation: 11888

Angular2: Injecting Router in myExceptionHAndler

In my app.module.ts I have :

@NgModule({
    declarations: [
        AppComponent,
    ],
    imports: [
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,
        HttpModule
    ],
    providers: [
        {provide: ErrorHandler, useClass: MyExceptionHandler}
    ],
    bootstrap: [AppComponent],
})
export class AppModule {}

Then in my MyExceptionHandler:

import { Injectable } from "@angular/core"
import { Router } from "@angular/router"

@Injectable()
export class MyExceptionHandler {
    constructor (private _router: Router) {}

    handleError(error:any):void {
        ...
    }
}

However, I am having an error saying : Error: Error: Provider parse errors

If I use MyExceptionHandler as an usual provider, it works fine. So my guess would be that the ErrorHandler gets handled before the Router exactly exists. Anyway to fix this ?

Upvotes: 1

Views: 642

Answers (1)

Aliaksei Maniuk
Aliaksei Maniuk

Reputation: 1674

According to https://github.com/angular/angular/issues/9843 working code will look like:

import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';

@Injectable()
export class GlobalErrorHandler extends ErrorHandler {
    private _router: Router;
    constructor(private _injector: Injector) {
        // The true parameter tells Angular to rethrow exceptions, 
        // so operations like 'bootstrap' will result in an error
        // when an error happens. If we do not rethrow, 
        // bootstrap will always succeed.
        super(true);
    }

    handleError(error: any): void {
        // Delegate to the default handler.
        super.handleError(error);

        if (!this._router) {
            this._router = this._injector.get(Router);
        }

        // TODO: log error and then redirect to 500 page.
        this._router.navigate(['/errors/500']);
    }
}

Upvotes: 4

Related Questions