How to connect / disable the base error class

How can I switch to the "patching" (or replace) the Error base class so that wherever someone throw new Error() in the code base (or try to throw away everything that comes from Error ), what will actually be created , is a certain replacement class (which has additional fields, logic).

I understand that this is far from the best practice, and it was not intended for your typical JS development scenario, it meant for some sandbox environment where arbitrary user code was run.

I tried something like this (which didn't work):

 OurError.prototype = Object.create(Error.prototype); Error.prototype = OurError.prototype; 

Itโ€™s clear that I donโ€™t know enough about prototypes to understand what Iโ€™m doing. Acquainted with some pointers or a simple example.

+5
source share
1 answer

You can always add additional methods to Error.prototype and use them later, like this (in ES6):

 Error.prototype.hello = function() { console.log(`Hello from ${this.constructor.name}!`); } const a = new Error(); a.hello(); // outputs "Hello from Error" class MyError extends Error {}; const b = new MyError(); b.hello(); // outputs "Hello from MyError" 

You can also completely replace the Error class as follows:

 class ImprovedError { constructor() { console.log(`I am an ${this.constructor.name}!`); } }; Error = ImprovedError; const c = new Error(); // outputs "I am an ImprovedError" 

Remember that replacing the Error class can completely have some adverse consequences and unpredictable results when interacting with external dependencies (libraries), since they can expect and call methods of the original Error class.

For more information about the methods and methods of the Error class, see here.

+3
source

Source: https://habr.com/ru/post/1273732/


All Articles