8

My custom Error class:

function MyError(message) {
  this.message = message || "";
}

MyError.prototype          = new Error();
MyError.prototype.name     = "MyError";
MyError.prototype.toString = function() {
  return "[" + this.name + "] " + this.message;
};

If I run throw new MyError("test") then FF/IE console shows a default message instead of the expected [MyError] test.

How do I get the JS engine to use my toString() method?

Bobby B
  • 2,287
  • 2
  • 24
  • 47

2 Answers2

3

This is how I would inherit Error (tested and working on FF v20):

function MyError(message) {
    this.message = message || "";
}

MyError.prototype = Object.create(Error.prototype); // see the note
MyError.prototype.name = "MyError";
MyError.prototype.toString = function () { 
    return "[" + this.name + "] " + this.message;
}

console.log(new MyError("hello").toString()); // "[MyError] hello"

Note that old browsers may not support Object.create (ES5 syntax), you can use this shim to make it work.

fardjad
  • 20,031
  • 6
  • 53
  • 68
  • Unfortunately this doesn't exhibit the expected behavior when you do this: `throw new MyError("hello");` it still shows a default message. The way listed above is functionally equivalent to this, but a bit safer. I have a feeling this has to do with the browser's JS engine, and so I cannot change it. – Bobby B May 05 '13 at 17:40
  • Actually `throw new MyError('hello')` works fine for me in **FF**. – fardjad May 05 '13 at 17:43
  • 1
    @BobbyB You're probably right, since `Error` class is bound to native code, the behavior will depend on the JavaScript engine implementation. Anyways [here](http://i.stack.imgur.com/nWlv5.png)'s a screenshot of the code running on my browser. – fardjad May 05 '13 at 19:01
3

I may be mistaken, but I think the console output in this case is controlled by the JS engine, and so you cannot format it as I've done above.

Bobby B
  • 2,287
  • 2
  • 24
  • 47