【问题标题】:Property 'code' does not exist on type 'Error'“错误”类型上不存在属性“代码”
【发布时间】:2017-03-01 15:52:13
【问题描述】:

如何访问 Error.code 属性? 我收到 Typescript 错误,因为“错误”类型上不存在属性“代码”。

this.authCtrl.login(user, {
   provider: AuthProviders.Password,
   method: AuthMethods.Password
}).then((authData) => {
    //Success
}).catch((error) => {
   console.log(error); // I see a code property
   console.log(error.code); //error
})

或者还有其他方法可以制作自定义错误消息吗?我想用另一种语言显示错误。

【问题讨论】:

    标签: angular typescript firebase angularfire2


    【解决方案1】:

    您必须从 catch 将类型转换为错误参数,即

    .catch((error:any) => {
        console.log(error);
        console.log(error.code);
    });
    

    也可以通过这种方式直接访问code属性

    .catch((error) => {
        console.log(error);
        console.log(error['code']);
    });
    

    【讨论】:

      【解决方案2】:

      真正的问题是 Node.js 定义文件没有导出正确的错误定义。它使用以下错误(并且不导出):

      interface Error {
          stack?: string;
      }
      

      它导出的实际定义在 NodeJS 命名空间中:

      export interface ErrnoException extends Error {
          errno?: number;
          code?: string;
          path?: string;
          syscall?: string;
          stack?: string;
      }
      

      因此以下类型转换将起作用:

      .catch((error: NodeJS.ErrnoException) => {
          console.log(error);
          console.log(error.code);
      })
      

      这似乎是 Node 定义中的一个缺陷,因为它与 new Error() 中的对象实际包含的内容不一致。 TypeScript 将强制执行接口错误定义。

      【讨论】:

      • 不是一个完整的解决方案。完整的解决方案还将显示需要添加的导入语句才能“拥有”NodeJS 符号。
      • @SzczepanHołyszewski 这个答案对我很有效,不需要额外的import
      【解决方案3】:
      export default class ResponseError extends Error {
          code: number;
          message: string;
          response: {
              headers: { [key: string]: string; };
              body: string;
          };
      }
      

      【讨论】:

        猜你喜欢
        • 2018-01-29
        • 2022-09-23
        • 2019-07-20
        • 2019-02-18
        • 2019-01-21
        • 2016-08-13
        • 2021-05-17
        • 2019-01-12
        • 1970-01-01
        相关资源
        最近更新 更多