Search code examples
angulardependency-injectionangular2-servicesangular2-injection

Angular2 - How do I inject a service into a custom exception handler


I have a custom exception handler like this in which I'm trying to inject a service (ErrorReportingService)

import { ExceptionHandler, Injectable } from '@angular/core';
import {ErrorReportingService  } from '../services/ErrorReportingService';

@Injectable()
export class InsightsExceptionHandler extends ExceptionHandler {
    constructor(private _errorReporter: ErrorReportingService) {
        super(null, null);
    }

call(error, stackTrace = null, reason = null) {
    this._errorReporter.logError(error);

    }
}

The service I'm trying to inject looks like this

import { Http, Response } from '@angular/http';
import { Injectable, Inject } from '@angular/core';

@Injectable()
export class ErrorReportingService {
    private ErrorReportingUrl = `/property/insights/api/errorreporting`;
    constructor(private _http: Http) { }

    logError(error: any) {
        var body = JSON.stringify(error);
        this._http.post(this.ErrorReportingUrl, body, null);
    }
}

The ErrorReportingService is registered under providers of the app component.

I have also tried injecting the service differently like this:

export class InsightsExceptionHandler extends ExceptionHandler {
    private _errorReporter: ErrorReportingService;
    constructor( @Inject(ErrorReportingService) errorReporter: ErrorReportingService) {
        super(null, null);
        this._errorReporter = errorReporter;
    }
......

I get this error when trying to run the app:

Error: (SystemJS) EXCEPTION: Error during instantiation of ApplicationRef_! (ApplicationRef -> ApplicationRef_).
ORIGINAL EXCEPTION: No provider for ErrorReportingService! (ExceptionHandler -> ErrorReportingService)
ORIGINAL STACKTRACE:
Error: DI Exception

Solution

  • I guess in your application main file where you are bootstrapping your application, you must be using something similar to below for Exception handling,

    Add all the services you need in the bootstrap provider itself,

    bootstrap(
    <YourAppComponent>,
    [
        // inject all the services which you need here 
        // so that they can be injected wherever required
    
        ErrorReportingService,
        provide(ExceptionHandler, {
            useClass: InsightsExceptionHandler 
        })
    ]).catch(err => console.error(err));