Reputation: 2209
I have an ErrorHandler
that I use to log all exceptions & then redirect user to generic error page. The problem is that this does work only if the exception that is handled occured outside of any lifecycle hooks (or constructor). method. Consider the following example with ngOnInit
:
class MyErrorHandler implements ErrorHandler {
constructor(private injector: Injector) { }
handleError(error) {
// log error
var router = this.injector.get(Router);
router.navigate['/error'];
}
}
The error handler is called correctly. However, the router.navigate works only when exception occured after initialization of component.
Doesn't work:
import { Component, OnInit} from '@angular/core';
@Component({
template: ''
})
export class SampleComponent implements OnInit{
ngOnInit() {
throw Error(`Boom!`);
}
}
Works as expected:
import { Component, OnInit} from '@angular/core';
@Component({
template: `<button (click)="handleClick()">click me</button>`
})
export class SampleComponent{
private handleClick(): void{
throw Error(`Boom!`);
}
}
Am I missing something or how can I make this work? I suppose I can use windows.location.href
, but that will reload the page which is something I would rather avoid.
Upvotes: 2
Views: 1058
Reputation: 2209
After some time I feel like the best solution is indeed to 'redirect' application to an error page using 'window.location.href'
. You never know what kind of error you end up with & in some cases the application could become totally broken.
Upvotes: 1
Reputation: 354
Injection in MyErrorHandler isn't correct.
Change { provide: ErrorHandler, useClass: MyErrorHandler }
in app.module.ts on
{
provide: ExceptionHandler,
useFactory: (router) => {
return new MyErrorHandler(router);
},
deps: [Router]
}
So now you have properly injected router.
Upvotes: 0