Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to throw error for destructuring non-existent key

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)
}
like image 990
A. L Avatar asked Apr 25 '18 11:04

A. L


1 Answers

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");
            }            
        }
    });
}
like image 76
gurvinder372 Avatar answered Sep 30 '22 05:09

gurvinder372