I created some custom Erros in my application and I wanted to check for them later using the constructor name. The problem is that when I extend Error in my classes, the constructor.name is always "Error", not the name I actually gave to it.
I was doing some tests and noticed that this happens with the Error class, but not with any other custom class I create. e.g.:
class CustomClass {
constructor(msg) {}
}
class OtherClass extends CustomClass {
constructor(msg) {
super(msg);
}
class CustomError extends Error {
constructor(msg) {
super(msg);
}
}
const e = new CustomError("There was an error");
const otherClass = new OtherClass("This is a class");
console.log(otherClass.constructor.name); // "OtherClass" <- ok!
console.log(e.constructor.name); // "Error" <- not ok! expected "CustomError"
Does anyone knows why this happens?
I thought I could do something like:
class CustomError extends Error {
constructor(msg) {
super(msg);
}
getName() {
return "CustomError";
}
}
const e = new CustomError("There was an error");
if(e.getName() == "CustomError") {
// do stuff
}
But then I get: TypeError: e.getName is not a function
EDIT
Following @samanime suggestion, I updated my node version to 8.8.1 and was able to find a partial solution.
Changing the syntax a little bit I got:
const FileSystemException = module.exports = class FileSystemException extends Error {
constructor(msg) {
super(msg);
}
getName() {
return "FileSystemException";
}
}
const e = new FileSystemException("There was an error");
// Running node app.js
console.log(e.constructor.name); // "FileSystemException"
console.log(e.getName()); // "FileSystemException"
// Running babel-node app.js
console.log(e.constructor.name); // "Error"
console.log(e.getName()); // "TypeError: e.getName is not a function"
Still, it would be awesome if someone could make it work with babel so I can use import/export statements without having to wait for node v9.4 LTS.
Using:
node v8.8.1
babel-node v6.26.0 w/ "es2015" and "stage-0" presets
thanks!
It seems to work just fine in this simple example:
class CustomError extends Error {
constructor(msg) {
super(msg);
}
}
const error = new CustomError()
console.log(error.constructor.name);
console.log(error instanceof CustomError);
console.log(error instanceof Error);
That is running with native class support (in Chrome).
It is possible that it isn't an issue with your syntax, but an issue with your transpiler. You probably want to dig through the transpiled code itself and see if it is doing anything special with Error that it doesn't with normal classes.
The fact that your getName() example didn't work also seems to indicate something funky is going on. Your examples you've posted look good. Double-check the code you are trying to run actually matches them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With