0

I developed a custom error handler which implements Angular2 Error Handler class. My custom error handler uses a logger service to log errors. The code looks like as follows:

export class CustomErrorHandler implements ErrorHandler {
    constructor(private logger: LoggerService) {}

    handleError(error: any): void {
        logger.error('....');
    }
}

However, since the logger service uses Angular2 router, I cannot inject the logger service to the custom error handler! Running the above code throws the following exception! Error: Provider parse errors:↵Cannot instantiate cyclic dependency!

2
  • Why does logger service use router? there are no routes involved with service. Services are supposed to be singletons. Commented Mar 2, 2017 at 23:45
  • It's because our logger service uses a remote logger to send logs to another online service. Commented Mar 6, 2017 at 17:27

1 Answer 1

1

You need to inject manually, to avoid the cyclic dependency problem because this class is created before the providers, your code should be:

import { Injectable, Injector } from '@angular/core';
import { Logger } from '...';

@Injectable()
export class CustomErrorHandler implements ErrorHandler {
    constructor(private injector: Injector) {}

    handleError(error: any): void {
        const logger = this.injector.get(Logger);
        logger.error('....');
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.