Errors
The structured error hierarchy
Every binal error is a subclass of BinalError, so catching BinalError catches all of them. Each error carries the field path, byte/bit offset, expected value, and actual value where they are known, so failures are actionable instead of bare messages.
BinalError— base class for all binal errors.SchemaError— the model definition is invalid. Raised at class definition (eager compilation) or at first use for forward references: conflicting markers, aWhenorLengthOfnaming a field that does not exist or comes later, aTaggedUnionon a non-union field, an unframedlist[bytes], and similar.ValidationError— a value violates a declared constraint, a strict type check, or a model-level__binal_validate__hook. Carriespath,expected,received, andoffset(the byte offset when it is known). A derived length that does not fit its integer type is stored at construction and raisesValidationErrorat encode.EncodeError— a value cannot be encoded. Carriespath,offset,expected, andreceived.encode()never mutates the instance: derived lengths, counts, and checksums are computed into a local dict.DecodeError— binary data cannot be decoded. Carriespath,offset,expected,available(a byte count),received(an offending value), andreason(a short machine-readable string such as"Unexpected end of input","Unexpected trailing data", or"Missing terminator").is_incompletemarks an error that means the input ended mid-field, andclaimedis the byte count the failing read needed.
from dataclasses import field
from typing import Annotated
from binal import (
BinaryModel,
DecodeError,
LengthOf,
Prefixed,
Sized,
UInt16,
ValidationError,
)
class Packet(BinaryModel, byte_order="big"):
payload: Annotated[bytes, Prefixed(UInt16)]
class SizedPacket(BinaryModel, byte_order="big"):
length: Annotated[UInt16, LengthOf("payload")] = field(init=False)
payload: Annotated[bytes, Sized("length")]
try:
Packet.decode(b"\x00\x05Hi") # truncated: 5 promised, 2 present
except DecodeError as e:
e.path # "Packet.payload"
e.offset # 2, the byte offset where the failure happened
e.reason # "Unexpected end of input"
print(e) # path, message, offset, expected, available, reason
try:
# The derived length 70000 does not fit UInt16; it is stored at
# construction and fails here, at encode.
SizedPacket(payload=b"x" * 70000).encode()
except ValidationError as e:
e.path # "SizedPacket.length"
e.expected # "integer between 0 and 65535"
e.received # 70000 decode() rejects trailing data; decode_partial() allows it and reports how many bytes the record consumed. Streaming readers distinguish incomplete input from invalid input by branching on DecodeError.is_incomplete (plus claimed, the byte count the failing read needed), never on the reason string — a malformed input that happens to raise “Unexpected end of input” must not be buffered until end of input. That is how IncrementalParser and the async reader tell the two apart.