Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 808
J-Yen Avatar asked Oct 19 '16 20:10

J-Yen


2 Answers

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.

like image 178
Brent Avatar answered Oct 04 '22 13:10

Brent


You have to cast a type to the error param from catch i.e.

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

or you can access the code property directly in this manner

.catch((error) => {
    console.log(error);
    console.log(error['code']);
});
like image 44
koech Avatar answered Oct 04 '22 12:10

koech