How to handle template errors (and other errors) in angular 2?

白昼怎懂夜的黑 提交于 2020-01-01 05:20:17

问题


When ever there is a template error in angular 2, the entire application fails to work.

Shouldn't only the component that had the template that caused the error, fail to work and the rest of the application be working fine?

How to handle errors so that the application won't stop being responsive when an error occurs?


回答1:


You can use custom ErrorHandler:

class MyErrorHandler implements ErrorHandler {
  handleError(error) {
    // do something with the exception
  }
}
@NgModule({
  providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
})
class MyModule {}



回答2:


Using ? mark is a solution around this while binding an object/array property to the template.

"user?.name?.firstname"

Looking for the more consolidated solution where we should able to handle template binding errors when huge data object comes from API and adding ? for each property in not a stable and lengthy solution.



来源:https://stackoverflow.com/questions/43040698/how-to-handle-template-errors-and-other-errors-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!