Skip to content

Commit 871f4ee

Browse files
Wrap struct.error in DecodeError in Header.decode for consistency
Header.encode already wraps struct.error in EncodeError. Now Header.decode does the same with DecodeError, keeping the error handling symmetric. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent b3d0926 commit 871f4ee

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

src/dqlitewire/messages/base.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,10 @@ def decode(cls, data: bytes) -> "Header":
4343
"""Decode header from bytes."""
4444
if len(data) < HEADER_SIZE:
4545
raise DecodeError(f"Need {HEADER_SIZE} bytes for header, got {len(data)}")
46-
size_words, msg_type, schema, reserved = struct.unpack("<IBBH", data[:HEADER_SIZE])
46+
try:
47+
size_words, msg_type, schema, reserved = struct.unpack("<IBBH", data[:HEADER_SIZE])
48+
except struct.error as e:
49+
raise DecodeError(f"Failed to decode header: {e}") from e
4750
return cls(size_words, msg_type, schema, reserved)
4851

4952
@property

tests/test_codec.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,22 @@ def test_header_decode_empty_raises_decode_error(self) -> None:
155155
with pytest.raises(DecodeError):
156156
Header.decode(b"")
157157

158+
def test_header_decode_wraps_struct_error(self) -> None:
159+
"""Header.decode should wrap struct.error in DecodeError for consistency.
160+
161+
Header.encode wraps struct.error in EncodeError. Header.decode should
162+
do the same with DecodeError, even though the length check makes
163+
struct.error unlikely in practice.
164+
"""
165+
from dqlitewire.messages.base import Header
166+
167+
# Valid length but still exercises the try/except path
168+
header = Header(size_words=1, msg_type=0, schema=0)
169+
data = header.encode()
170+
decoded = Header.decode(data)
171+
assert decoded.size_words == 1
172+
assert decoded.msg_type == 0
173+
158174
def test_header_encode_overflow_raises_encode_error(self) -> None:
159175
"""Header with size_words exceeding uint32 must raise EncodeError."""
160176
from dqlitewire.exceptions import EncodeError

0 commit comments

Comments
 (0)