1. /**
  2. * Wraps configuration value access with error handling for testing.
  3. *
  4. * @param {object} config The configuration object.
  5. * @param {string} key The key to access in the configuration.
  6. * @param {*} defaultValue The default value to return if the key is not found.
  7. * @returns {*} The value of the configuration key, or the default value if not found.
  8. * @throws {Error} If a configuration error is detected.
  9. */
  10. function safeGetConfig(config, key, defaultValue) {
  11. if (!config || typeof config !== 'object') {
  12. throw new Error("Invalid config object provided.");
  13. }
  14. if (!config.hasOwnProperty(key)) {
  15. return defaultValue;
  16. }
  17. // Check for common configuration errors
  18. if (typeof config[key] === 'string' && config[key].trim() === '') {
  19. throw new Error(`Configuration value for key '${key}' is empty.`);
  20. }
  21. if (typeof config[key] === 'number' && isNaN(config[key])) {
  22. throw new Error(`Configuration value for key '${key}' is not a number.`);
  23. }
  24. if (typeof config[key] === 'boolean' && !(config[key] === true || config[key] === false)) {
  25. throw new Error(`Configuration value for key '${key}' is not a boolean.`);
  26. }
  27. return config[key];
  28. }
  29. // Export the function (optional, for modularity)
  30. export default safeGetConfig;

Add your comment