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?
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.
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.
toString() ). This method is inherited by every object descended from Object , but can be overridden by descendant objects (for example, Number. prototype. toString() ).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With