/**
* Wraps configuration value access with error handling for testing.
*
* @param {object} config The configuration object.
* @param {string} key The key to access in the configuration.
* @param {*} defaultValue The default value to return if the key is not found.
* @returns {*} The value of the configuration key, or the default value if not found.
* @throws {Error} If a configuration error is detected.
*/
function safeGetConfig(config, key, defaultValue) {
if (!config || typeof config !== 'object') {
throw new Error("Invalid config object provided.");
}
if (!config.hasOwnProperty(key)) {
return defaultValue;
}
// Check for common configuration errors
if (typeof config[key] === 'string' && config[key].trim() === '') {
throw new Error(`Configuration value for key '${key}' is empty.`);
}
if (typeof config[key] === 'number' && isNaN(config[key])) {
throw new Error(`Configuration value for key '${key}' is not a number.`);
}
if (typeof config[key] === 'boolean' && !(config[key] === true || config[key] === false)) {
throw new Error(`Configuration value for key '${key}' is not a boolean.`);
}
return config[key];
}
// Export the function (optional, for modularity)
export default safeGetConfig;
Add your comment