Avernikoz
Avernikoz

Reputation: 513

Can't redefine Error.prototype.toString in Google Chrome

I am trying to redefine method toString of Error.prototype object, I can't do it in Google Chrome Canary, but I can do it in Firefox.

You can try to do it by your own, here is the code:

Error.prototype.toString = () => 'booooka'
throw new Error('Message, that have never been shown') // "booooka" in Firefox, "Message" in Google Chrome
  1. What is a problem doing this in Google Chrome?
  2. How I can do this in Google Chrome?

Firefox: 57.0.4 Chrome: 66.0.3356.0 (Official Build) canary (64-bit)

P.S. I have tried to paste this code to jsbin/jsfiddle, but I have the same result as in the Chrome. I am confused, maybe you can help me with that.

Thank you.

Upvotes: 1

Views: 283

Answers (2)

Ry-
Ry-

Reputation: 225125

Chrome lets you override toString just fine, but its console shows you the error’s stack instead of its toString(). Since the stack property is defined as an own property instead of being assigned to, there’s no neat way to override it (and possibly no way to override it period).

Consider this type of constructor:

const defineProperty = Object.defineProperty;

const Error = function () {
    defineProperty(this, 'stack', {
        configurable: true,
        writable: true,
        value: '…',
    });
};

I’m not aware of any way at all to change the value of new Error().stack in this context compared to what the constructor set.

That’s probably a good thing, though. What’s your goal?

Upvotes: 1

Osvaldo Maria
Osvaldo Maria

Reputation: 361

Adding to the previous answer, if you do :

throw new Error('Message, that have never been shown').toString(); 

'bookah' will be shown, so the issue is related with the implementation of the Error class rather than with overriding prototype properties

Upvotes: 1

Related Questions