[FIXED] Property 'code' does not exist on type 'Error'

Issue

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.

Solution

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

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

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.

Answered By – Brent

Answer Checked By – Dawn Plyler (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published