Tag Archives: NodeJS

Error subclasses may lose their message property

You have probably already seen a code like this:

try {
  throw new Error('Oh, nooooo!');
} catch (e) {
  console.log(e.message);            // Oh, nooooo!
  console.log(e instanceof Error);   // true
}

If you create many of those blocks, sooner or later you will decide that you are going to use custom error classes, even in JavaScript. It may seem to be a great idea to implement them this way:

function OhNoooError() {
  Error.call(this, "Oh, nooooo!");
  this.name = "OhNoooError";
}

But you may be surprised by the results:

try {
  throw new OhNoooError();
} catch (e) {
  console.log(e.message);                 // undefined
  console.log(e instanceof OhNoooError);  // true
  console.log(e instanceof Error);        // false
}

So the error you catch is not a classic error (does not inherit from the Error base class), and it does not have a message property! Oh, nooooooooooo!

Here is one way to fix it:

OhNoooError.prototype = Object.create(Error.prototype);
OhNoooError.prototype.constructor = OhNoooError;

function OhNoooError() {
  this.message = "Oh, nooooo!";
  this.name = "OhNoooError";
}

And now you have a much nicer output:

try {
  throw new OhNoooError();
} catch (e) {
  console.log(e.message);                 // Oh, nooooo!
  console.log(e instanceof OhNoooError);  // true
  console.log(e instanceof Error);        // true
}

The point is that you have to set the message property explicitly in the derived class – even if you use the extends keyword in CoffeeScript to do the inheritance magic.

 

Technorati-címkék: ,
Advertisements

Hey WebStorm, don’t search in the node_modules folder!

How annoying is that whatever you search for in a node.js project, WebStorm gives you thousand hits from the node_modules folder?

Calm down, and go to the Project window, right click on the problematic folder, and click Mark Directory As –> Excluded:

webstorm-exclude-folder-from-search

The folder won’t disappear from the Project window, but won’t pollute your search results any more.

You can undo this in the same place: Mark Directory As –> Cancel Exclusion

webstorm-exclude-folder-from-search-cancel

 

Technorati-címkék: ,