8

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?

4
  • 2
    What is wrong here? plnkr.co/edit/mvNJ61VJUlI5oITQJzaN?p=preview Commented Jan 10, 2017 at 18:43
  • Thank you for the plunker. Yeah, it looks like it's working fine there. My app is an Angular1 / Angular2 hybrid. I don't know for sure yet, but I'm guessing that that's causing issues and is the reason why the custom ErrorHandler isn't working for me. Commented Jan 12, 2017 at 13:50
  • 1
    maybe it's one of those rare times when it calls for this question having dual angular/angularjs tags Commented Aug 19, 2017 at 13:49
  • Template errors are raising during compilation phase before ErrorHandler is initialized Commented Sep 27, 2017 at 16:40

1 Answer 1

1

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.