如何为解析不存在的密钥抛出错误

时间:2018-04-25 11:28:11

标签: javascript ecmascript-6

所以我想对一个对象进行解构,如果其中一个键不存在则会抛出错误。我尝试了try catch,但它没有用。我想要替代if (variable === undefined)

let obj = {test : "test"}

try {
	let { test, asdf } = obj 
  console.log("worked")
}
catch (error) {
	console.error(error)
}

2 个答案:

答案 0 :(得分:3)

如果提取了不存在的属性,请使用proxy抛出错误

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
            }            
        }
    });
}

<强>演示

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");
            }            
        }
    });
}

答案 1 :(得分:0)

try-catch处理runtime错误,捕获您明确抛出的异常或错误。因此,在解构中,当找不到匹配密钥时不会抛出这样的错误。要检查是否存在,您需要明确地为其创建检查。像这样的东西,

&#13;
&#13;
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');
}
&#13;
&#13;
&#13;

这是因为解构的工作方式与我们将对象值分配给另一个值(如

)的方式相同
let obj = {test : "test"}
var test = obj.test;
var asdf = obj.asdf;

在这里,执行obj.asdf会在undefined中为您提供asdf,并且不会抛出任何异常。因此,您无法使用try-catch