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)
}
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)
}
Share
Improve this question
asked Apr 25, 2018 at 11:28
A. LA. L
12.7k29 gold badges98 silver badges179 bronze badges
1
- Have a look at this – Bergi Commented Apr 25, 2018 at 13:13
2 Answers
Reset to default 7Use 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");
}
}
});
}
The try-catch
work for the runtime
errors, catching exceptions or error you throw explicitly. Thus, in destructuring, there is no such error thrown when the matching key is not found. To check the existence you need to explicitly create a check for it. Something like this,
let obj = {test : "test"}
let { test, asdf } = obj
if(test){
console.log('worked');
} else {
console.log('not worked');
}
if(asdf){
console.log('worked');
} else {
console.log('not worked');
}
This is because the destructuring works the same way as we assign the object value to another value like,
let obj = {test : "test"}
var test = obj.test;
var asdf = obj.asdf;
Here, doing obj.asdf
will give you undefined
in asdf
and does not throw any exception. Thus, you cannot use try-catch
for that.