So I'd like to destructure an object and have it throw an error if one of the keys didn't exist. I tried a try catch
but it didn't work. And I'd like an alternative to just if (variable === undefined)
let obj = {test : "test"}
try {
let { test, asdf } = obj
console.log("worked")
}
catch (error) {
console.error(error)
}
Use proxy to throw the error if a non-existent property is fetched
let obj = {
test: "test"
};
try
{
let { test, asdf} = getProxy(obj);
console.log("worked");
}
catch (error)
{
console.error(error)
}
function getProxy(obj) {
return new Proxy(obj, { //create new Proxy object
get: function(obj, prop) { //define get trap
if( prop in obj )
{
return obj[prop];
}
else
{
throw new Error("No such property exists"); //throw error if prop doesn't exists
}
}
});
}
Demo
let obj = {
test: "test"
};
try
{
let { test, asdf} = getProxy(obj);
console.log("worked");
}
catch (error)
{
console.error(error)
}
function getProxy(obj) {
return new Proxy(obj, {
get: function(obj, prop) {
if( prop in obj )
{
return obj[prop];
}
else
{
throw new Error("No such property exists");
}
}
});
}
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