“错误"类型上不存在属性“代码" [英] Property 'code' does not exist on type 'Error'

查看:48
本文介绍了“错误"类型上不存在属性“代码"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于“错误"类型上不存在属性“代码"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆