Imagine I have the following code:
const object = {};
// an error should be thrown
object.property.someMethod();
// an error should be thrown
object.foo;
Is it possible to throw an error when someMethod()
is called or if any other non-existing property is called?
I guess that I need to do something with it's prototype, to throw an Error. However, I'm not sure what exactly I should do.
Any help would be appreciated.
Yes, using a Proxy
with a handler.get()
trap:
const object = new Proxy({}, {
get (target, key) {
throw new Error(`attempted access of nonexistent key \`${key}\``);
}
})
object.foo
If you want to modify an existing object with this behavior, you can use Reflect.has()
to check for property existence and determine whether to forward the access using Reflect.get()
or throw
:
const object = new Proxy({
name: 'Fred',
age: 42,
get foo () { return this.bar }
}, {
get (target, key, receiver) {
if (Reflect.has(target, key)) {
return Reflect.get(target, key, receiver)
} else {
throw new Error(`attempted access of nonexistent key \`${key}\``)
}
}
})
console.log(object.name)
console.log(object.age)
console.log(object.foo)
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