Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to throw an error when using a property of an object?
In JavaScript, objects contain properties in key-value format. When accessing non-existent properties, JavaScript returns undefined instead of throwing an error. However, you can implement custom error handling to throw errors when invalid properties are accessed.
Default Behavior: Accessing Non-existent Properties
By default, JavaScript returns undefined for non-existent properties:
<html>
<body>
<h2>Default behavior when accessing object properties</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>
The value of prop5 is: This is a nested object. The value of prop3 is: ! The value of prop6 is: undefined
Method 1: Using the 'in' Operator
The in operator checks if a property exists in an object. You can use it to validate properties before access:
Syntax
if (key in obj) {
// property exists
} else {
throw new Error('Property not found');
}
Example
<html>
<body>
<h3>Using the 'in' operator to throw error for invalid properties</h3>
<div id="content"></div>
<script>
let content = document.getElementById('content');
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>Error: " + e.message;
}
</script>
</body>
</html>
table_name: table1 Error: table_price1 is not a valid property name.
Method 2: Using Object.defineProperty()
The Object.defineProperty() method allows you to define custom getters that throw errors when specific properties are accessed:
Syntax
Object.defineProperty(obj_name, 'prop_name', {
get: () => {
throw new Error('Property access denied');
}
});
Parameters
obj_name ? The target object to add the property to
prop_name ? The property name to define
descriptor ? An object containing the getter function
Example
<html>
<body>
<h3>Using defineProperty() to throw error on property access</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: " + empty_obj.prop1;
} catch (err) {
content.innerHTML = "Error: " + err.message;
}
</script>
</body>
</html>
Error: You cannot access prop1 property
Method 3: Using Proxy Constructor
The Proxy constructor creates a wrapper that intercepts property access operations, allowing you to implement custom error handling:
Syntax
let proxy_obj = new Proxy(target_obj, {
get: function (target, prop) {
// Custom validation and error throwing
}
});
Example
<html>
<body>
<h3>Using Proxy to control property access</h3>
<div id="content"></div>
<script>
let content = document.getElementById('content');
let targetObj = {
prop1: 'Hello',
prop5: 'Allowed property'
};
let proxy_obj = new Proxy(targetObj, {
get: function (target, prop) {
if (prop !== 'prop5') {
throw new Error('You are only allowed to access prop5');
}
return target[prop];
}
});
try {
content.innerHTML += "Accessing prop5: " + proxy_obj.prop5 + "<br>";
content.innerHTML += "Accessing prop1: " + proxy_obj.prop1;
} catch (e) {
content.innerHTML += "Error: " + e.message;
}
</script>
</body>
</html>
Accessing prop5: Allowed property Error: You are only allowed to access prop5
Comparison
| Method | Use Case | Performance | Flexibility |
|---|---|---|---|
| 'in' operator | Simple property validation | Fast | Basic |
| defineProperty() | Specific property control | Medium | Medium |
| Proxy | Complete object control | Slower | High |
Conclusion
You can throw custom errors when accessing object properties using the 'in' operator for validation, Object.defineProperty() for specific properties, or Proxy for comprehensive object control. Choose the method based on your specific requirements and performance needs.
