dyn_encoding/error.rs
1//! Codec error type.
2
3use crate::value::WireTypeId;
4
5/// Errors produced by the codec layer.
6///
7/// All codec implementations report through this single enum so the
8/// [`CodecRegistry`](crate::CodecRegistry) can return `&dyn WireCodec`
9/// without erasing per-codec error types behind another `Box<dyn _>`.
10#[derive(Debug, thiserror::Error)]
11pub enum CodecError {
12 /// The codec has no encoder/decoder registered for the requested
13 /// wire type id.
14 #[error("unknown wire type id: {0}")]
15 UnknownTypeId(WireTypeId),
16
17 /// The value handed to `encode` does not have the type the
18 /// registered encoder expects. This indicates a logic bug in the
19 /// caller: the [`WireTypeId`] on the value matches a registration,
20 /// but the underlying concrete type is something else.
21 #[error(
22 "type mismatch for wire type id {expected}: value did not downcast to the registered type"
23 )]
24 TypeMismatch {
25 /// The wire type id the codec saw on the value.
26 expected: WireTypeId,
27 },
28
29 /// Underlying serializer rejected the value.
30 #[error("encode failure: {0}")]
31 Encode(#[source] Box<dyn std::error::Error + Send + Sync>),
32
33 /// Underlying deserializer rejected the bytes.
34 #[error("decode failure: {0}")]
35 Decode(#[source] Box<dyn std::error::Error + Send + Sync>),
36}
37
38impl CodecError {
39 /// Wrap an arbitrary serializer error as an encode failure.
40 pub fn encode_failure<E>(err: E) -> Self
41 where
42 E: Into<Box<dyn std::error::Error + Send + Sync>>,
43 {
44 Self::Encode(err.into())
45 }
46
47 /// Wrap an arbitrary deserializer error as a decode failure.
48 pub fn decode_failure<E>(err: E) -> Self
49 where
50 E: Into<Box<dyn std::error::Error + Send + Sync>>,
51 {
52 Self::Decode(err.into())
53 }
54}