Home  >  Article  >  Web Front-end  >  How to throw an error when using an object's properties?

How to throw an error when using an object's properties?

WBOY
WBOYforward
2023-08-26 08:13:11526browse

How to throw an error when using an objects properties?

In JavaScript, objects contain properties in 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 object properties that do not exist in the object. In this case we get undefined value. Let us understand it through the following example.

Example (accessing object properties)

In the example below, we create the object and add some properties. Additionally, we've added some nested properties. After that, we try to access the "prop5" property, which is a nested property of "prop4". The user can observe its value in the output.

Additionally, we try to access the "prop6" property, but the object returns undefined because it does not 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 does not exist in the object, we can throw an error stating that the property does not exist in the object.

Here we will learn a different way of throwing errors when accessing object properties.

Using the "in" operator raises an error when accessing object properties

The "in" operator allows us to check if a property exists in an object. We can use a key as the left operand of the "in" operator and an object as the right operand.

We can check whether the attribute exists in the object. If not, we can throw an error.

grammar

Users can use the "in" operator according to the following syntax to throw errors when accessing object properties.

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

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

Example

In the example below, we create the table_obj object and add some key-value pairs. The function named get_property_value() checks whether the property exists in the object. If the property exists in the object, the property value is returned. Otherwise, it will throw an error.

In the try-catch block, we catch an error. In the output, the user can observe that the get_property_value() function throws an error for the "table_price1" property instead of returning an 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>

An error is thrown when accessing object properties using defineProperty() method

Javascript’s defineProperty() method allows us to add properties to objects. We can add getters for property descriptors that throw errors.

grammar

Users can use the defineProperty() method according to the following syntax to throw an error when accessing object properties.

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

In the above syntax, we pass the descriptor as the third parameter of the defineProperty() method. We can throw errors from the descriptor function of a specific property of an object.

parameter

  • Obj_name - This is the object name to which the attribute is added to the object.

  • Prop_name - This is the name of the property to be added to the object.

  • { get: () => { } } - It is the getters function for object properties.

Example

In the example below, we create an empty_obj object with zero properties. We use the defineProperties() method to add properties. As a descriptor, we added the get() method, which throws an error and displays an error message.

In the output, the user can observe that when we try to access the "prop1" property it throws an error.

<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>

Using the Proxy() constructor to access object properties raises an error

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

grammar

Users can use the following syntax to use the Proxy() constructor to throw errors when accessing object properties.

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

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

Example

In the following example, we use the Proxy() constructor to create a proxy for the targetObj object. When creating the proxy we check if the user accessed the "prop5" property. If not, we will always throw an error. This means that the "prop5" property can only be accessed from the object. However, it will return an undefined value for the "prop5" property because we haven't defined it in the object yet.

<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>

The above is the detailed content of How to throw an error when using an object's properties?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete