How do I go about "patching" (or replacing) the basic Error class, so that wherever anyone does throw new Error()
in the code base (or tries to throw anything that derives from Error) what will actually be instantiated is some replacement class (that has some extra fields, logic).
I do realize this is far from being a best practice, and it's not meant for your typical JS development scenario, it's meant for some sandbox environment where arbitrary user-code gets run.
I tried something like this (which did not work):
OurError.prototype = Object.create(Error.prototype);
Error.prototype = OurError.prototype;
Clearly I don't know enough about prototypes to understand what I'm doing. Would appreciate some pointers or a simple example.
You can always add more methods to the Error.prototype
, and use them afterwards, 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 replace the Error class completely like this:
class ImprovedError {
constructor() {
console.log(`I am an ${this.constructor.name}!`);
}
};
Error = ImprovedError;
const c = new Error(); // outputs "I am an ImprovedError"
Be aware that replacing the Error
class completely might have some adverse consequences and unpredictable results when interacting with external dependencies (libraries) since they may expect and call the methods of the original Error
class.
For more info on the Error
class methods and behaviour see here
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