“错误”类型中不存在属性“代码”

时间:2016-10-19 20:31:58

标签: angular typescript firebase angularfire2

如何访问Error.code属性? 我得到一个Typescript错误,因为属性'code'在'Error'类型上不存在。

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
})

或者是否有另一种方法来制作自定义错误消息?我想用另一种语言显示错误。

3 个答案:

答案 0 :(得分:10)

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

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

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

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

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

{{1}}

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

答案 1 :(得分:4)

你必须将一个类型转换为来自catch的错误参数。

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

或者您可以直接以这种方式访问​​代码属性

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

答案 2 :(得分:1)

export default class ResponseError extends Error {
    code: number;
    message: string;
    response: {
        headers: { [key: string]: string; };
        body: string;
    };
}
相关问题