admin管理员组文章数量:1320627
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.
本文标签: javascripthow to throw error for destructuring nonexistent keyStack Overflow
版权声明:本文标题:javascript - how to throw error for destructuring non-existent key - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742071572a2419155.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论