1use alloc::borrow::{Cow, ToOwned};
4use alloc::format;
5use alloc::string::{String, ToString};
6use core::fmt;
7
8use crate::decode::{DecodeError, DecodeErrorKind};
9use crate::version::Version;
10
11#[derive(Clone, Debug, PartialEq, Eq, Hash)]
24#[non_exhaustive]
25pub enum ErrorCode {
26 FormatViolation,
28 GenericError,
30 InternalError,
32 MessageTypeNotSupported,
38 NotImplemented,
40 NotSupported,
42 OccurrenceConstraintViolation,
44 PropertyConstraintViolation,
46 ProtocolError,
48 RpcFrameworkError,
51 SecurityError,
53 TypeConstraintViolation,
55 Other(String),
57}
58
59impl ErrorCode {
60 #[must_use]
65 pub fn as_wire(&self, version: Version) -> &str {
66 let legacy = version == Version::V1_6;
67 match self {
68 ErrorCode::FormatViolation => {
69 if legacy {
70 "FormationViolation"
71 } else {
72 "FormatViolation"
73 }
74 }
75 ErrorCode::GenericError => "GenericError",
76 ErrorCode::InternalError => "InternalError",
77 ErrorCode::MessageTypeNotSupported => {
78 if legacy {
79 "GenericError"
80 } else {
81 "MessageTypeNotSupported"
82 }
83 }
84 ErrorCode::NotImplemented => "NotImplemented",
85 ErrorCode::NotSupported => "NotSupported",
86 ErrorCode::OccurrenceConstraintViolation => {
87 if legacy {
88 "OccurenceConstraintViolation"
90 } else {
91 "OccurrenceConstraintViolation"
92 }
93 }
94 ErrorCode::PropertyConstraintViolation => "PropertyConstraintViolation",
95 ErrorCode::ProtocolError => "ProtocolError",
96 ErrorCode::RpcFrameworkError => {
97 if legacy {
98 "GenericError"
99 } else {
100 "RpcFrameworkError"
101 }
102 }
103 ErrorCode::SecurityError => "SecurityError",
104 ErrorCode::TypeConstraintViolation => "TypeConstraintViolation",
105 ErrorCode::Other(code) => code.as_str(),
106 }
107 }
108
109 #[must_use]
111 pub fn parse(code: &str) -> Self {
112 match code {
113 "FormatViolation" | "FormationViolation" => ErrorCode::FormatViolation,
114 "GenericError" => ErrorCode::GenericError,
115 "InternalError" => ErrorCode::InternalError,
116 "MessageTypeNotSupported" => ErrorCode::MessageTypeNotSupported,
117 "NotImplemented" => ErrorCode::NotImplemented,
118 "NotSupported" => ErrorCode::NotSupported,
119 "OccurrenceConstraintViolation" | "OccurenceConstraintViolation" => {
120 ErrorCode::OccurrenceConstraintViolation
121 }
122 "PropertyConstraintViolation" => ErrorCode::PropertyConstraintViolation,
123 "ProtocolError" => ErrorCode::ProtocolError,
124 "RpcFrameworkError" => ErrorCode::RpcFrameworkError,
125 "SecurityError" => ErrorCode::SecurityError,
126 "TypeConstraintViolation" => ErrorCode::TypeConstraintViolation,
127 other => ErrorCode::Other(other.to_owned()),
128 }
129 }
130
131 #[must_use]
133 pub fn is_defined_in(&self, version: Version) -> bool {
134 match self {
135 ErrorCode::RpcFrameworkError | ErrorCode::MessageTypeNotSupported => {
136 version != Version::V1_6
137 }
138 ErrorCode::Other(_) => false,
139 _ => true,
140 }
141 }
142}
143
144impl fmt::Display for ErrorCode {
145 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147 f.write_str(self.as_wire(Version::V2_1))
148 }
149}
150
151pub const ERROR_DESCRIPTION_MAX_LEN: usize = 255;
153
154fn cap_description(text: &str) -> String {
160 match text.char_indices().nth(ERROR_DESCRIPTION_MAX_LEN) {
161 Some((cut, _)) => text[..cut].to_owned(),
162 None => text.to_owned(),
163 }
164}
165
166#[derive(Clone, Debug, PartialEq)]
168pub struct CallError {
169 pub code: ErrorCode,
171 pub description: String,
173 pub details: serde_json::Value,
175}
176
177impl CallError {
178 #[must_use]
180 pub fn new(code: ErrorCode, description: impl Into<String>) -> Self {
181 Self {
182 code,
183 description: cap_description(&description.into()),
184 details: serde_json::Value::Object(serde_json::Map::new()),
185 }
186 }
187
188 #[must_use]
190 pub fn with_details(mut self, details: serde_json::Value) -> Self {
191 self.details = details;
192 self
193 }
194
195 #[must_use]
197 pub fn not_implemented(action: &str) -> Self {
198 Self::new(
199 ErrorCode::NotImplemented,
200 format!("unknown action {action:?}"),
201 )
202 }
203
204 #[must_use]
206 pub fn not_supported(action: &str) -> Self {
207 Self::new(
208 ErrorCode::NotSupported,
209 format!("action {action:?} is not supported"),
210 )
211 }
212
213 #[must_use]
215 pub fn internal(description: impl Into<String>) -> Self {
216 Self::new(ErrorCode::InternalError, description)
217 }
218
219 #[must_use]
221 pub fn security(description: impl Into<String>) -> Self {
222 Self::new(ErrorCode::SecurityError, description)
223 }
224}
225
226impl From<DecodeError> for CallError {
227 fn from(error: DecodeError) -> Self {
230 let code = match error.kind {
231 DecodeErrorKind::Format => ErrorCode::FormatViolation,
232 DecodeErrorKind::Occurrence => ErrorCode::OccurrenceConstraintViolation,
233 DecodeErrorKind::Type => ErrorCode::TypeConstraintViolation,
234 DecodeErrorKind::Property => ErrorCode::PropertyConstraintViolation,
235 DecodeErrorKind::UnknownField | DecodeErrorKind::Protocol => ErrorCode::ProtocolError,
238 DecodeErrorKind::UnsupportedAction => ErrorCode::NotSupported,
239 };
240 let mut details = serde_json::Map::new();
241 if !error.path.is_empty() {
242 details.insert(
243 "path".to_string(),
244 serde_json::Value::String(error.path.clone()),
245 );
246 }
247 details.insert(
248 "reason".to_string(),
249 serde_json::Value::String(error.reason.clone()),
250 );
251 Self {
252 code,
253 description: cap_description(&error.to_string()),
254 details: serde_json::Value::Object(details),
255 }
256 }
257}
258
259impl fmt::Display for CallError {
260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261 if self.description.is_empty() {
262 write!(f, "{}", self.code)
263 } else {
264 write!(f, "{}: {}", self.code, self.description)
265 }
266 }
267}
268
269#[cfg(feature = "std")]
270impl std::error::Error for CallError {}
271
272#[derive(Clone, Debug)]
276pub struct CallErrorRef<'a> {
277 pub code: ErrorCode,
279 pub description: Cow<'a, str>,
281 pub details: Cow<'a, serde_json::value::RawValue>,
283}
284
285impl CallErrorRef<'_> {
286 #[must_use]
288 pub fn to_call_error(&self) -> CallError {
289 CallError {
290 code: self.code.clone(),
291 description: self.description.clone().into_owned(),
292 details: serde_json::from_str(self.details.get())
293 .unwrap_or_else(|_| serde_json::Value::Object(serde_json::Map::new())),
294 }
295 }
296
297 #[must_use]
299 pub fn into_owned(self) -> CallErrorRef<'static> {
300 CallErrorRef {
301 code: self.code,
302 description: Cow::Owned(self.description.into_owned()),
303 details: Cow::Owned(self.details.into_owned()),
304 }
305 }
306}
307
308impl PartialEq for CallErrorRef<'_> {
309 fn eq(&self, other: &Self) -> bool {
311 self.code == other.code
312 && self.description == other.description
313 && self.details.get() == other.details.get()
314 }
315}
316
317impl From<CallError> for CallErrorRef<'static> {
318 fn from(error: CallError) -> Self {
319 CallErrorRef {
320 code: error.code,
321 description: Cow::Owned(cap_description(&error.description)),
322 details: Cow::Owned(
323 serde_json::value::to_raw_value(&error.details).unwrap_or_else(|_| {
324 serde_json::value::RawValue::from_string("{}".to_string()).expect("valid")
325 }),
326 ),
327 }
328 }
329}
330
331impl From<&CallError> for CallErrorRef<'static> {
332 fn from(error: &CallError) -> Self {
333 CallErrorRef {
334 code: error.code.clone(),
335 description: Cow::Owned(cap_description(&error.description)),
336 details: Cow::Owned(
337 serde_json::value::to_raw_value(&error.details).unwrap_or_else(|_| {
338 serde_json::value::RawValue::from_string("{}".to_string()).expect("valid")
339 }),
340 ),
341 }
342 }
343}