I found the solution below. It passes the testError successfully. Could you please share your opinion about this code?
const originalError=globalThis.Error;
const Error=(new (class {
Error=function(msg){
if(this instanceof Error){
const error=new originalError(msg);
if(msg)
this.message=error.message;
this.stack=error.stack;
return this;
}
return new Error(msg);
}})).Error;
Object.getOwnPropertyNames(originalError.prototype).forEach((prop) => {
if (prop !== 'constructor') {
Object.defineProperty(Error.prototype, prop, Object.getOwnPropertyDescriptor(originalError.prototype, prop));
}
});
Object.getOwnPropertyNames(originalError).forEach((prop) => {
if (prop !== 'prototype')
Object.defineProperty(Error, prop, Object.getOwnPropertyDescriptor(originalError, prop));
});
const errorTypes = [
'TypeError',
'ReferenceError',
'SyntaxError',
'RangeError',
'EvalError',
'URIError',
'AggregateError',
];
errorTypes.forEach((errorType) => {
const errorConstructor = globalThis[errorType];
if (errorConstructor) {
Object.setPrototypeOf(errorConstructor, Error);
Object.setPrototypeOf(errorConstructor.prototype, Error.prototype);
}
});
originalError.prepareStackTrace = function prepareStackTrace(err, stack) {
if(Object.getPrototypeOf(Object.getPrototypeOf(err))===originalError.prototype){
Object.setPrototypeOf(Object.getPrototypeOf(err), Error.prototype);
}
if (Error.prepareStackTrace) {
err.stack = Error.prepareStackTrace(err, stack);
}
return err.stack;
};
Object.defineProperty(globalThis, 'Error', {
value: Error,
writable: true,
configurable: true,
enumerable: false,
});
function testError(){
if(Object.hasOwn(Error,"caller") || Object.hasOwn(Error,"arguments") || Object.hasOwn(Error,"prepareStackTrace"))
return false;
try {
new Error()
} catch (error) {
return false;
}
try {
Error()
} catch (error) {
return false;
}
try {
Object.create(Error).toString()
} catch (error) {
if(error.stack.includes("Object.toString"))
return false
}
return new Error() instanceof Error && new TypeError() instanceof Error && Error() instanceof Error && TypeError() instanceof Error
}
console.log(`Error constructor patched: ${testError() ? 'success' : 'failed'}`);