8

我的自定义错误类:

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

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

如果我运行,throw new MyError("test")则 FF/IE 控制台会显示默认消息,而不是预期的[MyError] test.

如何让 JS 引擎使用我的toString()方法?

4

2 回答 2

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.

于 2013-05-05T17:35:40.690 回答
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.

于 2013-05-05T17:58:16.757 回答