Skip to content

Commit 3343b41

Browse files
committed
feat: allow DenoKvError to have no message argument
It used to always require a message string, which made it awkward to subclass for errors that don't want to define a message at init.
1 parent 848fac1 commit 3343b41

File tree

2 files changed

+21
-8
lines changed

2 files changed

+21
-8
lines changed

src/denokv/errors.py

+10-8
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,22 @@
11
from dataclasses import dataclass
22

3-
from denokv._pycompat.typing import cast
3+
from denokv._pycompat.typing import TYPE_CHECKING
44

55

66
@dataclass(init=False)
77
class DenoKvError(Exception):
8-
message: str
8+
# Define message for dataclass field metadata only, not type annotation.
9+
if not TYPE_CHECKING:
10+
message: str
911

10-
def __init__(self, message: str, *args: object) -> None:
11-
super().__init__(message, *args)
12-
if not isinstance(message, str):
13-
raise TypeError(f"first argument must be a str message: {message!r}")
12+
def __init__(self, *args: object) -> None:
13+
super(DenoKvError, self).__init__(*args)
1414

15-
@property # type: ignore[no-redef]
15+
@property
1616
def message(self) -> str:
17-
return cast(str, self.args[0])
17+
if args := self.args:
18+
return str(args[0])
19+
return type(self).__name__
1820

1921

2022
class DenoKvValidationError(ValueError, DenoKvError):

test/test_errors.py

+11
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,14 @@ def test_errors_are_regular_exceptions() -> None:
77
"""Errors must be caught by generic Exception handlers — not BaseException."""
88
with pytest.raises(Exception): # noqa: B017
99
raise DenoKvError("error")
10+
11+
12+
def test_DenoKvError_message() -> None:
13+
assert DenoKvError().message == "DenoKvError"
14+
assert DenoKvError("Foo bar").message == "Foo bar"
15+
16+
class CustomError(DenoKvError):
17+
pass
18+
19+
assert CustomError().message == "CustomError"
20+
assert CustomError("Bar baz").message == "Bar baz"

0 commit comments

Comments
 (0)