【发布时间】:2019-07-24 10:13:15
【问题描述】:
如果在我的组件模板中抛出未定义的错误,我正在尝试寻找一种方法来处理。发生这种情况时,应用程序将中断,所需的解决方案是导航到“应用程序错误”组件或将出错的组件替换为“应用程序错误”组件,以便应用程序保持正常运行状态。
【问题讨论】:
标签: angular typescript angular6
如果在我的组件模板中抛出未定义的错误,我正在尝试寻找一种方法来处理。发生这种情况时,应用程序将中断,所需的解决方案是导航到“应用程序错误”组件或将出错的组件替换为“应用程序错误”组件,以便应用程序保持正常运行状态。
【问题讨论】:
标签: angular typescript angular6
您可以在代码中使用 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}]
})
【讨论】:
没有通用的方法可以在一个地方捕获所有undefined。
仅当您编写的代码不安全或/且不够干净时才会出现此错误。
一些良好实践领域:
const myVar: string = null;
class MyClass {
public myAttr: string = 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
}
【讨论】: