Reputation: 5208
I am making use of the ErrorHandler in Angular. It works fine if i am working with only one module. When i am using multiple modules and want to use different error handlers in a specific child module, it does not work. Only the parent error handler is invoked.
RootModule
|--> provides CustomErrorHandler1
|
|--> ChildModule1
| |--> provides CustomErrorHandler2
|
|--> ChildModule2
|--> provides CustomErrorHandler1
If an error occures in ChildModule1 or ChildModule2 the error is always handled by the CustomErrorHandler1 instance of RootModule.
I am using lazy-loading to load those modules. Providing different instances of the same service works for all @Injectable()s except for the error handler.
Is it possible to provide those ErrorHandlers so that the errors in each module will be handled by the ErrorHandler provided in their module definition?
I created a sample repository at github. It can be run via ng serve
. If you click on "child1" an error is thrown by Childmodule1 and if you click on "child2" an error is thrown by Childmodule2.
Upvotes: 5
Views: 3442
Reputation: 5208
The answer is, that ErrorHandling just works for RootModules and the Angular Team is not planning to change that:
https://github.com/angular/angular/issues/22197
Upvotes: 3
Reputation: 3543
After some research I found out that
ErrorHandler => Provides a hook for centralized exception handling.
So I registered only 1 ErrorHandler
which intercepts all Exceptions
then I've delegated the error to the component based ErrorHandlers
and handled the data inside of them. Every child
component will have it's own Error
and based on instanceof
we are delegating error to the appropriate ErrorHandler
inside of the component
.
Note: The downside of this is that any Error
that passes error instanceof Error
check will be delegated to the Global registered handler
aka one inside of app.module.ts
Also I know that this approach might not be the best, but there isn't a possibility of registering multiple ErrorHandlers
that are per component
but rather one Global
one and then handling everything inside of it. Hope that this can help you resolve the issue in a proper way.
Also I've updated the nikola_gavric
branch so you can see what I did there
Upvotes: 3
Reputation: 133
Could you share the code from the Modules???
From what you point it doesn't make any sense since Angular when routes are lazyLoaded, creates a hierarchy of injectors in compilation. That should create the effect that your are looking for.
My suggestions are:
{ provide: ErrorHandler, useClass: CustomErrorHandlerX }
Upvotes: 0