最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

prototypal inheritance - Custom Javascript Error.toString() - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited May 5, 2013 at 17:33 Bobby B asked May 5, 2013 at 17:24 Bobby BBobby B 2,3253 gold badges25 silver badges48 bronze badges 6
  • Shouldn't it be MyError.prototype = Error.prototype? – fardjad Commented May 5, 2013 at 17:29
  • 1 A solution would be to not inherit from Error. – Denys Séguret Commented May 5, 2013 at 17:30
  • 1 @fardjad nope see here – Bobby B Commented May 5, 2013 at 17:30
  • @dystroy I guess that's true, but there are benefits to doing so (other standard and non-standard properties which are useful) – Bobby B Commented May 5, 2013 at 17:32
  • @BobbyB I know, that's why I only made a ment, not an answer. – Denys Séguret Commented May 5, 2013 at 17:41
 |  Show 1 more ment

2 Answers 2

Reset to default 4

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.

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.

发布评论

评论列表(0)

  1. 暂无评论