rocketmq_error/unified/
serialization.rs1use thiserror::Error;
21
22#[derive(Debug, Error)]
24pub enum SerializationError {
25 #[error("Encoding failed ({format}): {message}")]
27 EncodeFailed {
28 format: &'static str,
29 message: String,
30 },
31
32 #[error("Decoding failed ({format}): {message}")]
34 DecodeFailed {
35 format: &'static str,
36 message: String,
37 },
38
39 #[error("Invalid format: expected {expected}, got {got}")]
41 InvalidFormat { expected: &'static str, got: String },
42
43 #[error("Missing required field: {field}")]
45 MissingField { field: &'static str },
46
47 #[error("Invalid value for field '{field}': {reason}")]
49 InvalidValue { field: &'static str, reason: String },
50
51 #[error("UTF-8 encoding error: {0}")]
53 Utf8Error(#[from] std::str::Utf8Error),
54
55 #[cfg(feature = "with_serde")]
57 #[error("JSON error: {0}")]
58 JsonError(String),
59
60 #[error("Protobuf error: {0}")]
62 ProtobufError(String),
63}
64
65impl SerializationError {
66 #[inline]
68 pub fn encode_failed(format: &'static str, message: impl Into<String>) -> Self {
69 Self::EncodeFailed {
70 format,
71 message: message.into(),
72 }
73 }
74
75 #[inline]
77 pub fn decode_failed(format: &'static str, message: impl Into<String>) -> Self {
78 Self::DecodeFailed {
79 format,
80 message: message.into(),
81 }
82 }
83
84 #[inline]
86 pub fn invalid_format(expected: &'static str, got: impl Into<String>) -> Self {
87 Self::InvalidFormat {
88 expected,
89 got: got.into(),
90 }
91 }
92
93 #[inline]
95 pub fn missing_field(field: &'static str) -> Self {
96 Self::MissingField { field }
97 }
98}
99
100#[cfg(feature = "with_serde")]
101impl From<serde_json::Error> for SerializationError {
102 fn from(e: serde_json::Error) -> Self {
103 Self::JsonError(e.to_string())
104 }
105}
106
107#[cfg(test)]
108mod tests {
109 use super::*;
110
111 #[test]
112 fn test_serialization_error() {
113 let err = SerializationError::encode_failed("JSON", "unexpected token");
114 assert!(err.to_string().contains("Encoding failed"));
115 assert!(err.to_string().contains("JSON"));
116 }
117
118 #[test]
119 fn test_missing_field() {
120 let err = SerializationError::missing_field("broker_name");
121 assert_eq!(err.to_string(), "Missing required field: broker_name");
122 }
123}