How to catch built-in template errors in Angular 2?

Suppose I have the following component:

@Component({ template: '<div>{{foo.bar}}</div>' }) class DemoComponent { foo = undefined; } 

Note that I'm trying to access the bar property of undefined value. This causes an error similar to:

Error in DemoComponent class - built-in template: 1: 9 caused by: Cannot read the 'bar' property from undefined

I would like to catch this error using custom ErrorHandler :

 class LoggingErrorHandler implements ErrorHandler { constructor(private logger: Logger) { } handleError(error: any): void { this.logger.error(error); } } 

However, the handleError method handleError not called for template errors. My custom error handler works great for other errors - just pattern errors. So how can I catch template errors?

+6
source share
1 answer

You can create a template with *ngIf="!foo.bar" .

if this is the expected async request, you can use the asynchronous channel with a safe statement to just wait for the value without causing an error: (foo | async).bar

Is there a special reason to have a template error handler for this?

0
source

Source: https://habr.com/ru/post/1013952/


All Articles