How to throw an error when using a property of an object?


In JavaScript, an object contains the properties in the key-value format. We can access any property of an object using the property name by taking the object as a reference.

Sometimes, we try to access the object property that doesn’t exist in the object. In such cases, we get the undefined value. Let’s understand it by the example below.

Example (Accessing the Object Properties)

In the example below, we have created the object and added some properties. Also, we have added some nested properties. After that, we try to access the ‘prop5’ property which is a nested property of the ‘prop4.’ and users can observe its value in the output.

Also, we have tried to access the ‘prop6’ property and the object return undefined as it doesn’t exist in the object.

<html>
<body>
   <h2>Accessing the object properties in JavaScript</h2>
   <div id="content"> </div>
   <script>
      let content = document.getElementById('content');
      let object = {
         name: 'Shubham',
         prop1: 'Hello',
         prop2: 'World',
         prop3: '!',
         prop4: {
            prop5: 'This is a nested object.'
         }
      }
      content.innerHTML = "The value of prop5 is : " + object.prop4.prop5;
      content.innerHTML += "<br> The value of prop3 is : " + object.prop3;
      content.innerHTML += "<br> The value of prop6 is : " + object.prop6;
   </script>
</body>
</html>

So, whenever a property doesn’t exist in the object, we can throw an error saying the property doesn’t exist in the object.

Here, we will learn a different approach to throw an error while accessing the object properties.

Use the ‘in’ Operator to Throw an Error While Accessing the Object Properties

The ‘in’ operator allows us to check whether a property exists in the object. We can use the key as a left operand of the ‘in’ operator and the object as a right operand.

We can check if a property exists in the object. If not, we can throw an error.

Syntax

Users can follow the syntax below to use the ‘in’ operator to throw an error while accessing the object properties.

if(key in obj){
}else {
   // throw error
}

In the above syntax, the key is a property to check if it exists in the object.

Example

In the example below, we have created the table_obj object and added some key-value pairs. The function named get_property_value() checks if a property exists in the object. If the property exists in the object, it returns the property value. Otherwise, it throws an error.

In the try-catch block, we catch an error. In the output, users can observe that the get_property_value() function throws an error for the ‘table_price1’ property rather than returning the undefined value for the property.

<html>
<body>
   <h3>Using the <i> in </i> operator  to throw an error while accessing the object properties in JavaScript</h3>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      // creating an object for table details
      let table_obj = {
         table_name: "table1",
         table_type: "table",
         table_size: "10x10",
         table_color: "black",
         table_price: 1000
      }
      function get_property_value(key) {
         if (key in table_obj) {
            return table_obj[key];
         } else {
            throw new Error(key + " is not a valid property name.");
         }
      }
      try {
         content.innerHTML += "table_name : - " + get_property_value("table_name");
         content.innerHTML += "<br>" + get_property_value("table_price1");
      } catch (e) {
         content.innerHTML += "<br>" + e.message;
      }
   </script>
</body>
</html>

Throw an Error While Accessing the Object Properties Using the defineProperty() Method

The defineProperty() method of Javascript allows us to add the property to the object. We can add the getters for a property descriptor throwing an error.

Syntax

Users can follow the syntax below to use the defineProperty() method to throw an error while accessing the object properties.

Object.defineProperty(obj_name, 'prop_name', {
   get: () => {
      // throw an error
   }
});

In the above syntax, we have passed the descriptor as a third parameter of the defineProperty() method. We can throw an error from the descriptor function for a particular property of the object.

Parameters

  • Obj_name − It is the object's name to add the property to the object.

  • Prop_name − It is a property name to add to the object.

  • { get: () => { } } − It is a getters function for an object property.

Example

In the example below, we have created the empty_obj object with zero properties. We use the defineProperties() method to add property. As a descriptor, we have added the get() method throwing an error with an error message.

In the output, users can observe that it throws an error when we try to access the ‘prop1’ property.

<html>
<body>
   <h3>Using the <i> defineProperty() </i> method to throw an error while accessing the object properties in JavaScript </h3>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      let empty_obj = {};
      Object.defineProperty(empty_obj, 'prop1', {
         get: () => {
            throw new Error('You cannot access prop1 property');
         }
      });
      try {
         content.innerHTML = "The value of prop1 property in the empty object is " + empty_obj.prop1;
      }
      catch (err) {
         content.innerHTML = "The error is : - " + err;
      }
   </script>
</body>
</html>

Throw an Error Using the Proxy() Constructor While Accessing the Object Property

The Proxy() constructor allows us to create a proxy for an object and override all descriptors of objects, such as getters and setters. Here, we can override the getters() and write a new function that can throw an error.

Syntax

Users can use the syntax below to use the Proxy() constructor to throw an error while accessing the object properties.

let proxy_obj = new Proxy(target_Obj, {
   get: function (target, prop) {
      // throw error
   },
});

In the above syntax, target_obj is an object to create a proxy for it. We have passed the object containing the get() method as a second parameter. In the get() method, we can validate the object property and throw an error if the object property is invalid.

Example

In the example below, we have created the proxy for a targetObj object using the Proxy() constructor. While creating the proxy, we check whether users have accessed the ‘prop5’ property. If not, we always throw an error. It means only the ‘prop5’ property is accessed from the object. However, it will return an undefined value for the ‘prop5’ property as we haven’t defined it in the object.

<html>
<body>
   <h3>Using the <i> defineProperty() </i> method to throw an error while accessing the object properties in JavaScript </h3>
   <div id = "content"> </div>
   <script>
      let content = document.getElementById('content');
      let targetObj = {
         prop1: 'Hello',
      }
      let proxy_obj = new Proxy(targetObj, {
         get: function (target, prop) {
            if (prop != 'prop5') {
               throw new Error('You are only allowed to access prop5');
            }
         },
      });
      try {
         content.innerHTML += "The value of prop1 is: " + proxy_obj.prop1 + "<br>";
      } catch (e) {
         content.innerHTML += "The error is - " + e + "<br>";
      }
   </script>
</body>
</html>

Updated on: 05-Apr-2023

402 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements