I'm trying to get the error code when I catch an error, but it's always undefined.
How do I get the error code?
Here are two examples:
try {
const f = 4;
f = 9;
} catch (err) {
console.log(err.code);
console.log(err.message);
}
try {
d = 12;
} catch (err) {
console.log(err.code);
console.log(err.message);
}
Console:
undefined
Assignment to constant variable.
undefined
d is not defined
I work on Node.js v14.17.1.
A standard Javascript/Ecmascript error has no code property. See the Error docs for details.
The link you provide, from Node's Errors documentation pertains only to custom errors thrown by Node.js — Javascript errors thrown by, say, V8 will adhere to Javascript standard referenced in the 1st link above.
As the others commented try console.log(err) to see what the object looks like before trying to select properties from it.
I misunderstood the question with my original answer. To my understanding there is no .code property on the error object returned within a try catch block. Check out this documentation https://javascript.info/try-catch#error-object and try error.name.