Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch inline template errors in Angular 2?

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?

like image 763
battmanz Avatar asked Jan 10 '17 18:01

battmanz


1 Answers

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?

like image 169
FussinHussin Avatar answered Nov 13 '22 16:11

FussinHussin