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,
34 NotImplemented,
36 NotSupported,
38 OccurrenceConstraintViolation,
40 PropertyConstraintViolation,
42 ProtocolError,
44 RpcFrameworkError,
47 SecurityError,
49 TypeConstraintViolation,
51 Other(String),
53}
54
55impl ErrorCode {
56 #[must_use]
61 pub fn as_wire(&self, version: Version) -> &str {
62 let legacy = version == Version::V1_6;
63 match self {
64 ErrorCode::FormatViolation => {
65 if legacy {
66 "FormationViolation"
67 } else {
68 "FormatViolation"
69 }
70 }
71 ErrorCode::GenericError => "GenericError",
72 ErrorCode::InternalError => "InternalError",
73 ErrorCode::MessageTypeNotSupported => {
74 if legacy {
75 "GenericError"
76 } else {
77 "MessageTypeNotSupported"
78 }
79 }
80 ErrorCode::NotImplemented => "NotImplemented",
81 ErrorCode::NotSupported => "NotSupported",
82 ErrorCode::OccurrenceConstraintViolation => {
83 if legacy {
84 "OccurenceConstraintViolation"
86 } else {
87 "OccurrenceConstraintViolation"
88 }
89 }
90 ErrorCode::PropertyConstraintViolation => "PropertyConstraintViolation",
91 ErrorCode::ProtocolError => "ProtocolError",
92 ErrorCode::RpcFrameworkError => {
93 if legacy {
94 "GenericError"
95 } else {
96 "RpcFrameworkError"
97 }
98 }
99 ErrorCode::SecurityError => "SecurityError",
100 ErrorCode::TypeConstraintViolation => "TypeConstraintViolation",
101 ErrorCode::Other(code) => code.as_str(),
102 }
103 }
104
105 #[must_use]
107 pub fn parse(code: &str) -> Self {
108 match code {
109 "FormatViolation" | "FormationViolation" => ErrorCode::FormatViolation,
110 "GenericError" => ErrorCode::GenericError,
111 "InternalError" => ErrorCode::InternalError,
112 "MessageTypeNotSupported" => ErrorCode::MessageTypeNotSupported,
113 "NotImplemented" => ErrorCode::NotImplemented,
114 "NotSupported" => ErrorCode::NotSupported,
115 "OccurrenceConstraintViolation" | "OccurenceConstraintViolation" => {
116 ErrorCode::OccurrenceConstraintViolation
117 }
118 "PropertyConstraintViolation" => ErrorCode::PropertyConstraintViolation,
119 "ProtocolError" => ErrorCode::ProtocolError,
120 "RpcFrameworkError" => ErrorCode::RpcFrameworkError,
121 "SecurityError" => ErrorCode::SecurityError,
122 "TypeConstraintViolation" => ErrorCode::TypeConstraintViolation,
123 other => ErrorCode::Other(other.to_owned()),
124 }
125 }
126
127 #[must_use]
129 pub fn is_defined_in(&self, version: Version) -> bool {
130 match self {
131 ErrorCode::RpcFrameworkError | ErrorCode::MessageTypeNotSupported => {
132 version != Version::V1_6
133 }
134 ErrorCode::Other(_) => false,
135 _ => true,
136 }
137 }
138}
139
140impl fmt::Display for ErrorCode {
141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 f.write_str(self.as_wire(Version::V2_1))
144 }
145}
146
147pub const ERROR_DESCRIPTION_MAX_LEN: usize = 255;
149
150fn cap_description(text: &str) -> String {
156 match text.char_indices().nth(ERROR_DESCRIPTION_MAX_LEN) {
157 Some((cut, _)) => text[..cut].to_owned(),
158 None => text.to_owned(),
159 }
160}
161
162#[derive(Clone, Debug, PartialEq)]
164pub struct CallError {
165 pub code: ErrorCode,
167 pub description: String,
169 pub details: serde_json::Value,
171}
172
173impl CallError {
174 #[must_use]
176 pub fn new(code: ErrorCode, description: impl Into<String>) -> Self {
177 Self {
178 code,
179 description: cap_description(&description.into()),
180 details: serde_json::Value::Object(serde_json::Map::new()),
181 }
182 }
183
184 #[must_use]
186 pub fn with_details(mut self, details: serde_json::Value) -> Self {
187 self.details = details;
188 self
189 }
190
191 #[must_use]
193 pub fn not_implemented(action: &str) -> Self {
194 Self::new(
195 ErrorCode::NotImplemented,
196 format!("unknown action {action:?}"),
197 )
198 }
199
200 #[must_use]
202 pub fn not_supported(action: &str) -> Self {
203 Self::new(
204 ErrorCode::NotSupported,
205 format!("action {action:?} is not supported"),
206 )
207 }
208
209 #[must_use]
211 pub fn internal(description: impl Into<String>) -> Self {
212 Self::new(ErrorCode::InternalError, description)
213 }
214
215 #[must_use]
217 pub fn security(description: impl Into<String>) -> Self {
218 Self::new(ErrorCode::SecurityError, description)
219 }
220}
221
222impl From<DecodeError> for CallError {
223 fn from(error: DecodeError) -> Self {
226 let code = match error.kind {
227 DecodeErrorKind::Format => ErrorCode::FormatViolation,
228 DecodeErrorKind::Occurrence => ErrorCode::OccurrenceConstraintViolation,
229 DecodeErrorKind::Type => ErrorCode::TypeConstraintViolation,
230 DecodeErrorKind::Property => ErrorCode::PropertyConstraintViolation,
231 DecodeErrorKind::UnknownField | DecodeErrorKind::Protocol => ErrorCode::ProtocolError,
234 DecodeErrorKind::UnsupportedAction => ErrorCode::NotSupported,
235 };
236 let mut details = serde_json::Map::new();
237 if !error.path.is_empty() {
238 details.insert(
239 "path".to_string(),
240 serde_json::Value::String(error.path.clone()),
241 );
242 }
243 details.insert(
244 "reason".to_string(),
245 serde_json::Value::String(error.reason.clone()),
246 );
247 Self {
248 code,
249 description: cap_description(&error.to_string()),
250 details: serde_json::Value::Object(details),
251 }
252 }
253}
254
255impl fmt::Display for CallError {
256 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257 if self.description.is_empty() {
258 write!(f, "{}", self.code)
259 } else {
260 write!(f, "{}: {}", self.code, self.description)
261 }
262 }
263}
264
265#[cfg(feature = "std")]
266impl std::error::Error for CallError {}
267
268#[derive(Clone, Debug)]
272pub struct CallErrorRef<'a> {
273 pub code: ErrorCode,
275 pub description: Cow<'a, str>,
277 pub details: Cow<'a, serde_json::value::RawValue>,
279}
280
281impl CallErrorRef<'_> {
282 #[must_use]
284 pub fn to_call_error(&self) -> CallError {
285 CallError {
286 code: self.code.clone(),
287 description: self.description.clone().into_owned(),
288 details: serde_json::from_str(self.details.get())
289 .unwrap_or_else(|_| serde_json::Value::Object(serde_json::Map::new())),
290 }
291 }
292
293 #[must_use]
295 pub fn into_owned(self) -> CallErrorRef<'static> {
296 CallErrorRef {
297 code: self.code,
298 description: Cow::Owned(self.description.into_owned()),
299 details: Cow::Owned(self.details.into_owned()),
300 }
301 }
302}
303
304impl PartialEq for CallErrorRef<'_> {
305 fn eq(&self, other: &Self) -> bool {
307 self.code == other.code
308 && self.description == other.description
309 && self.details.get() == other.details.get()
310 }
311}
312
313impl From<CallError> for CallErrorRef<'static> {
314 fn from(error: CallError) -> Self {
315 CallErrorRef {
316 code: error.code,
317 description: Cow::Owned(cap_description(&error.description)),
318 details: Cow::Owned(
319 serde_json::value::to_raw_value(&error.details).unwrap_or_else(|_| {
320 serde_json::value::RawValue::from_string("{}".to_string()).expect("valid")
321 }),
322 ),
323 }
324 }
325}
326
327impl From<&CallError> for CallErrorRef<'static> {
328 fn from(error: &CallError) -> Self {
329 CallErrorRef {
330 code: error.code.clone(),
331 description: Cow::Owned(cap_description(&error.description)),
332 details: Cow::Owned(
333 serde_json::value::to_raw_value(&error.details).unwrap_or_else(|_| {
334 serde_json::value::RawValue::from_string("{}".to_string()).expect("valid")
335 }),
336 ),
337 }
338 }
339}