From 6fe032fac90d129856a36e3e43ba979a25d4417d Mon Sep 17 00:00:00 2001 From: pierrocknroll Date: Tue, 29 Apr 2025 12:01:06 +0200 Subject: [PATCH] :goal_net: Improve error handling --- src/configcore/errors.py | 12 ++++++++++++ src/configcore/loglevel.py | 8 ++++---- tests/configcore/settings_test.py | 10 ++++++---- 3 files changed, 22 insertions(+), 8 deletions(-) create mode 100644 src/configcore/errors.py diff --git a/src/configcore/errors.py b/src/configcore/errors.py new file mode 100644 index 0000000..be12137 --- /dev/null +++ b/src/configcore/errors.py @@ -0,0 +1,12 @@ +class ConfigError(Exception): + """Base class for package exceptions.""" + + +class UnknownLogLevelError(ConfigError): + """Raised when a specified log level doesn't match any known log level.""" + + def __init__(self, invalid_value: str, valid_values: list) -> None: + """Raise the error with correct message.""" + super().__init__( + f"Invalid log level '{invalid_value}'. Must be one of: {valid_values}", + ) diff --git a/src/configcore/loglevel.py b/src/configcore/loglevel.py index 06fd4d2..c784799 100644 --- a/src/configcore/loglevel.py +++ b/src/configcore/loglevel.py @@ -2,6 +2,8 @@ from enum import IntEnum from typing import Self +from .errors import UnknownLogLevelError + class LogLevel(IntEnum): """Represents the different log levels.""" @@ -23,12 +25,10 @@ def from_str(cls, value: str) -> Self: LogLevel enum value. Raises: - ValueError: If the string doesn't match any log level. + UnknownLogLevelError: If the string doesn't match any log level. """ try: return cls[value.upper()] except KeyError as e: valid_values = [e.name for e in cls] - raise ValueError( - f"Invalid log level '{value}'. Must be one of: {valid_values}", - ) from e + raise UnknownLogLevelError(value, valid_values) from e diff --git a/tests/configcore/settings_test.py b/tests/configcore/settings_test.py index 1f31e6c..08f97cb 100644 --- a/tests/configcore/settings_test.py +++ b/tests/configcore/settings_test.py @@ -1,10 +1,10 @@ import os import pytest -from pydantic import ValidationError from pydantic_settings import SettingsConfigDict from src.configcore import Environment, LogLevel, Settings +from src.configcore.errors import UnknownLogLevelError class TestSettings: @@ -56,10 +56,12 @@ def test_invalid_log_level(self) -> None: """Test that invalid log level raises error.""" os.environ["LOG_LEVEL"] = "invalid" - with pytest.raises(ValidationError) as exc_info: + with pytest.raises(UnknownLogLevelError) as exc_info: Settings() - assert "log_level" in str(exc_info.value) - assert len(exc_info.value.errors()) == 1 + assert str(exc_info.value) == ( + "Invalid log level 'invalid'. " + "Must be one of: ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']" + ) def test_is_env_production(self) -> None: """Test is_env_production helper method."""