Reputation: 2296
Suppose I have the following component:
@Component({
template: '<div>{{foo.bar}}</div>'
})
class DemoComponent {
foo = undefined;
}
Notice how I'm attempting to access the bar
property of an undefined value. This throws an error similar to:
Error in class DemoComponent - inline template:1:9 caused by: Cannot read property 'bar' of undefined
I would like to catch this error using a custom ErrorHandler
:
class LoggingErrorHandler implements ErrorHandler {
constructor(private logger: Logger) {
}
handleError(error: any): void {
this.logger.error(error);
}
}
However, the handleError
method is not called for template errors. My custom error handler works fine for other errors -- just not template errors. So how do I catch template errors?
Upvotes: 8
Views: 2058
Reputation: 1814
You could create a template with *ngIf="!foo.bar"
.
if it is an async request you are waiting on, you could use the async pipe with the safe operator to just wait for the value without throwing an error: (foo | async).bar
is there a particular reason to have a template error handler for this?
Upvotes: 1