Skip to main content

rocketmq_error/unified/
serialization.rs

1// Copyright 2023 The RocketMQ Rust Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Serialization and deserialization errors
16
17use thiserror::Error;
18
19/// Serialization/Deserialization errors
20#[derive(Debug, Error)]
21pub enum SerializationError {
22    /// Encoding failed
23    #[error("Encoding failed ({format}): {message}")]
24    EncodeFailed { format: &'static str, message: String },
25
26    /// Decoding failed
27    #[error("Decoding failed ({format}): {message}")]
28    DecodeFailed { format: &'static str, message: String },
29
30    /// Invalid data format
31    #[error("Invalid format: expected {expected}, got {got}")]
32    InvalidFormat { expected: &'static str, got: String },
33
34    /// Missing required field
35    #[error("Missing required field: {field}")]
36    MissingField { field: &'static str },
37
38    /// Invalid field value
39    #[error("Invalid value for field '{field}': {reason}")]
40    InvalidValue { field: &'static str, reason: String },
41
42    /// UTF-8 encoding error
43    #[error("UTF-8 encoding error: {0}")]
44    Utf8Error(#[from] std::str::Utf8Error),
45
46    /// JSON serialization error
47    #[cfg(feature = "with_serde")]
48    #[error("JSON error: {0}")]
49    JsonError(String),
50
51    /// Protobuf serialization error
52    #[error("Protobuf error: {0}")]
53    ProtobufError(String),
54
55    /// Event serialization failed
56    #[error("Event serialization failed: {0}")]
57    EventSerializationFailed(String),
58
59    /// Event deserialization failed
60    #[error("Event deserialization failed: {0}")]
61    EventDeserializationFailed(String),
62
63    /// Invalid event type
64    #[error("Invalid event type: {0}")]
65    InvalidEventType(i16),
66
67    /// Unknown event type
68    #[error("Unknown event type: {0}")]
69    UnknownEventType(i16),
70}
71
72impl SerializationError {
73    /// Create an encode failed error
74    #[inline]
75    pub fn encode_failed(format: &'static str, message: impl Into<String>) -> Self {
76        Self::EncodeFailed {
77            format,
78            message: message.into(),
79        }
80    }
81
82    /// Create a decode failed error
83    #[inline]
84    pub fn decode_failed(format: &'static str, message: impl Into<String>) -> Self {
85        Self::DecodeFailed {
86            format,
87            message: message.into(),
88        }
89    }
90
91    /// Create an invalid format error
92    #[inline]
93    pub fn invalid_format(expected: &'static str, got: impl Into<String>) -> Self {
94        Self::InvalidFormat {
95            expected,
96            got: got.into(),
97        }
98    }
99
100    /// Create a missing field error
101    #[inline]
102    pub fn missing_field(field: &'static str) -> Self {
103        Self::MissingField { field }
104    }
105
106    /// Create an event serialization failed error
107    #[inline]
108    pub fn event_serialization_failed(message: impl Into<String>) -> Self {
109        Self::EventSerializationFailed(message.into())
110    }
111
112    /// Create an event deserialization failed error
113    #[inline]
114    pub fn event_deserialization_failed(message: impl Into<String>) -> Self {
115        Self::EventDeserializationFailed(message.into())
116    }
117
118    /// Create an invalid event type error
119    #[inline]
120    pub fn invalid_event_type(type_id: i16) -> Self {
121        Self::InvalidEventType(type_id)
122    }
123
124    /// Create an unknown event type error
125    #[inline]
126    pub fn unknown_event_type(type_id: i16) -> Self {
127        Self::UnknownEventType(type_id)
128    }
129}
130
131#[cfg(feature = "with_serde")]
132impl From<serde_json::Error> for SerializationError {
133    fn from(e: serde_json::Error) -> Self {
134        Self::JsonError(e.to_string())
135    }
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    #[test]
143    fn test_serialization_error() {
144        let err = SerializationError::encode_failed("JSON", "unexpected token");
145        assert_eq!(err.to_string(), "Encoding failed (JSON): unexpected token");
146
147        let err = SerializationError::decode_failed("Protobuf", "invalid length");
148        assert_eq!(err.to_string(), "Decoding failed (Protobuf): invalid length");
149
150        let err = SerializationError::invalid_format("u32", "string".to_string());
151        assert_eq!(err.to_string(), "Invalid format: expected u32, got string");
152
153        let err = SerializationError::missing_field("broker_name");
154        assert_eq!(err.to_string(), "Missing required field: broker_name");
155
156        let err = SerializationError::InvalidValue {
157            field: "timeout",
158            reason: "negative".to_string(),
159        };
160        assert_eq!(err.to_string(), "Invalid value for field 'timeout': negative");
161
162        let err = SerializationError::ProtobufError("missing tag".to_string());
163        assert_eq!(err.to_string(), "Protobuf error: missing tag");
164
165        let err = SerializationError::event_serialization_failed("error");
166        assert_eq!(err.to_string(), "Event serialization failed: error");
167
168        let err = SerializationError::event_deserialization_failed("error");
169        assert_eq!(err.to_string(), "Event deserialization failed: error");
170
171        let err = SerializationError::invalid_event_type(1);
172        assert_eq!(err.to_string(), "Invalid event type: 1");
173
174        let err = SerializationError::unknown_event_type(1);
175        assert_eq!(err.to_string(), "Unknown event type: 1");
176    }
177
178    #[test]
179    fn test_utf8_error() {
180        let invalid_utf8 = vec![0, 159, 146, 150];
181        let result = std::str::from_utf8(&invalid_utf8);
182        let utf8_error = result.err().unwrap();
183        let err = SerializationError::from(utf8_error);
184        assert_eq!(
185            err.to_string(),
186            "UTF-8 encoding error: invalid utf-8 sequence of 1 bytes from index 1"
187        );
188    }
189
190    #[cfg(feature = "with_serde")]
191    #[test]
192    fn test_json_error() {
193        let json_result: Result<serde_json::Value, _> = serde_json::from_str("{ invalid }");
194        let json_error = json_result.err().unwrap();
195        let err = SerializationError::from(json_error);
196        assert!(err.to_string().contains("JSON error"));
197    }
198}