Mike
Mike

Reputation: 333

javascript print error when calling missing object property

I would like to write a proxy object to automatically print errors when calling some property in original object which is not found.

const proxyObjectFn = () => {
  const _obj = Object.assign({}, originalObject);

  const get = (key) => {
    const value = _obj[key];
    if (value === undefined) {
      console.error(`${key} not found`);
    }
    return value;
  };

  return {
    get,
  };
};

const proxyObject = proxyObjectFn();

export default proxyObject;

// caller
proxyObject.get('someProperty')

This works, but is there any elegant way so that I can call through proxyObject.someProperty instead of proxyObject.get('someProperty')?

Update

Let me make it more specific. Actually I am writing a translation object.

Original object may be from json, like { "HELLO_KEY": "Hello World" }. I am to call like { label: _t.SOME_I18N_KEY } in UI display code, assuming _t is the proxy object above. I can print the warning to tell me there is missing translation.

Upvotes: 0

Views: 89

Answers (1)

Klaycon
Klaycon

Reputation: 11080

You can use the Proxy object:

const handler = {
  get: (obj, prop) => {
    if(!obj.hasOwnProperty(prop)) console.error(`${prop} not found`);
    return obj[prop];
  }
};

const _t = new Proxy({ "HELLO_KEY": "Hello World" }, handler);

console.log(_t.HELLO_KEY);
console.log(_t.SOME_NONEXISTENT_KEY);

Upvotes: 1

Related Questions