“错误"类型上不存在属性“代码"

“错误

问题描述:

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

How can i access the Error.code property? I get a Typescript error because the property 'code' does not exist on type '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
})

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

Or is there another way to make custom error messages? I want to show the errors in another language.

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

The real issue is that the Node.js definition file isn't exporting a proper Error definition. It uses the following for Error (and doesn't export this):

interface Error {
    stack?: string;
}

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

The actual definition it exports is in the NodeJS namespace:

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

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

So the following typecast will work:

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

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

This seems like a flaw in Node's definition, since it doesn't line up with what an object from new Error() actually contains. TypeScript will enforce the interface Error definition.