【问题标题】:How to catch "undefined" errors in Angular 6如何在 Angular 6 中捕获“未定义”错误
【发布时间】:2019-07-24 10:13:15
【问题描述】:

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

【问题讨论】:

    标签: angular typescript angular6


    【解决方案1】:

    您可以在代码中使用 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}]
    })
    

    【讨论】:

    • 这对 component.html 模板文件中发生的错误也有效吗?
    • 不会吧!唯一的办法就是写干净的代码!
    • 感谢您的回复,我正在寻找一种方法来发现我们可能错过的生产问题,我们已经遵守所有这些干净的编码标准
    【解决方案2】:

    没有通用的方法可以在一个地方捕获所有undefined。 仅当您编写的代码不安全或/且不够干净时才会出现此错误。

    一些良好实践领域:

    1. 初始化值
    const myVar: string = null;
    
    class MyClass {
      public myAttr: string = null
    }
    
    1. 如果不是 undefined 或 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

    【讨论】:

    猜你喜欢
    • 2018-09-27
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 2022-12-29
    • 1970-01-01
    • 2011-03-16
    相关资源
    最近更新 更多