Skip to content

Commit fb316f6

Browse files
Merge pull request #2 from inokufu/feature/errors
🥅 Improve error handling
2 parents e6eeb19 + 6fe032f commit fb316f6

3 files changed

Lines changed: 22 additions & 8 deletions

File tree

src/configcore/errors.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
class ConfigError(Exception):
2+
"""Base class for package exceptions."""
3+
4+
5+
class UnknownLogLevelError(ConfigError):
6+
"""Raised when a specified log level doesn't match any known log level."""
7+
8+
def __init__(self, invalid_value: str, valid_values: list) -> None:
9+
"""Raise the error with correct message."""
10+
super().__init__(
11+
f"Invalid log level '{invalid_value}'. Must be one of: {valid_values}",
12+
)

src/configcore/loglevel.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
from enum import IntEnum
33
from typing import Self
44

5+
from .errors import UnknownLogLevelError
6+
57

68
class LogLevel(IntEnum):
79
"""Represents the different log levels."""
@@ -23,12 +25,10 @@ def from_str(cls, value: str) -> Self:
2325
LogLevel enum value.
2426
2527
Raises:
26-
ValueError: If the string doesn't match any log level.
28+
UnknownLogLevelError: If the string doesn't match any log level.
2729
"""
2830
try:
2931
return cls[value.upper()]
3032
except KeyError as e:
3133
valid_values = [e.name for e in cls]
32-
raise ValueError(
33-
f"Invalid log level '{value}'. Must be one of: {valid_values}",
34-
) from e
34+
raise UnknownLogLevelError(value, valid_values) from e

tests/configcore/settings_test.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import os
22

33
import pytest
4-
from pydantic import ValidationError
54
from pydantic_settings import SettingsConfigDict
65

76
from src.configcore import Environment, LogLevel, Settings
7+
from src.configcore.errors import UnknownLogLevelError
88

99

1010
class TestSettings:
@@ -56,10 +56,12 @@ def test_invalid_log_level(self) -> None:
5656
"""Test that invalid log level raises error."""
5757
os.environ["LOG_LEVEL"] = "invalid"
5858

59-
with pytest.raises(ValidationError) as exc_info:
59+
with pytest.raises(UnknownLogLevelError) as exc_info:
6060
Settings()
61-
assert "log_level" in str(exc_info.value)
62-
assert len(exc_info.value.errors()) == 1
61+
assert str(exc_info.value) == (
62+
"Invalid log level 'invalid'. "
63+
"Must be one of: ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']"
64+
)
6365

6466
def test_is_env_production(self) -> None:
6567
"""Test is_env_production helper method."""

0 commit comments

Comments
 (0)