Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 379
Bobby B Avatar asked May 05 '13 17:05

Bobby B


People also ask

How do I use toString in JavaScript?

The toString() method returns a string as a string. The toString() method does not change the original string. The toString() method can be used to convert a string object into a string.

Is there a toString method in JavaScript?

toString . For user-defined Function objects, the toString method returns a string containing the source text segment which was used to define the function. JavaScript calls the toString method automatically when a Function is to be represented as a text value, e.g. when a function is concatenated with a string.

Can we override toString method in JavaScript?

toString() ). This method is inherited by every object descended from Object , but can be overridden by descendant objects (for example, Number. prototype. toString() ).


2 Answers

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.

like image 58
fardjad Avatar answered Sep 21 '22 07:09

fardjad


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.

like image 42
Bobby B Avatar answered Sep 24 '22 07:09

Bobby B