如何在Angular 6中捕获“未定义”错误

时间:2019-07-24 10:13:15

标签: angular typescript angular6

我正在尝试找到一种方法来处理是否在组件模板中引发了未定义的错误。发生这种情况时,应用程序将崩溃,所需的解决方案是导航到“应用程序错误”组件或将错误的组件替换为“应用程序错误”组件,以使应用程序保持运行状态。

2 个答案:

答案 0 :(得分:0)

您可以在代码上使用try / catch块,但是在较大的应用程序中进行管理可能很繁琐。相反,您可以通过从@ angular / core扩展ErrorHandler来创建自己的错误处理逻辑。

像这样的东西

import { ErrorHandler } from '@angular/core';

@Injectable()
export class YourErrorHandler implements ErrorHandler {

  handleError(error) {
    // your custom error handling logic    
  }
}

然后,像这样将其添加到您的根模块中;

@NgModule({   
  providers: [{provide: ErrorHandler, useClass: GlobalErrorHandler}]
})

答案 1 :(得分:0)

没有一种通用方法可以将所有undefined捕获在一个地方。 仅当您编写的代码不安全或/和不够清洁时才会发生此错误。

一些好的做法领域:

  1. 初始化值
const myVar: string = null;

class MyClass {
  public myAttr: string = null
}
  1. 仅设置值(如果未定义),null或两者都不是

// matches not null & not undefined
if (newVal != null) {
  myVar = newVal;
}

// matches only not undefined
if (newVal !== undefined) {
  myVar = newVal;
}

// matches only not null
if (newVal !== null) {
  myVar = newVal
}
  1. 检查对象路径

示例请参见此处:https://stackoverflow.com/a/2631198/3634274