属性 'code' 在类型 'Error' 上不存在

Property 'code' does not exist on type 'Error'

如何访问 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
})

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

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

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

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

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

真正的问题是 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 将强制执行接口错误定义。

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