Bobby B
Bobby B

Reputation: 2325

Custom Javascript Error.toString()

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?

Upvotes: 9

Views: 4033

Answers (2)

Bobby B
Bobby B

Reputation: 2325

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.

Upvotes: 4

fardjad
fardjad

Reputation: 20414

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.

Upvotes: 3

Related Questions