1use crate::mxc_common::mxc_error::{ApiFailure, MxcError, MxcErrorCode};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12pub enum ErrorCode {
13 MalformedRequest,
14 UnsupportedContainment,
15 UnsupportedPhase,
16 BackendUnavailable,
17 MalformedId,
18 StaleId,
19 NotProvisioned,
20 NotStarted,
21 AlreadyStarted,
22 AlreadyStopped,
23 PolicyValidation,
24 BackendError,
25}
26
27impl ErrorCode {
28 pub fn as_str(self) -> &'static str {
30 match self {
31 Self::MalformedRequest => "malformed_request",
32 Self::UnsupportedContainment => "unsupported_containment",
33 Self::UnsupportedPhase => "unsupported_phase",
34 Self::BackendUnavailable => "backend_unavailable",
35 Self::MalformedId => "malformed_id",
36 Self::StaleId => "stale_id",
37 Self::NotProvisioned => "not_provisioned",
38 Self::NotStarted => "not_started",
39 Self::AlreadyStarted => "already_started",
40 Self::AlreadyStopped => "already_stopped",
41 Self::PolicyValidation => "policy_validation",
42 Self::BackendError => "backend_error",
43 }
44 }
45}
46
47impl std::fmt::Display for ErrorCode {
48 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49 f.write_str(self.as_str())
50 }
51}
52
53impl ErrorCode {
54 fn to_internal(self) -> MxcErrorCode {
56 match self {
57 Self::MalformedRequest => MxcErrorCode::MalformedRequest,
58 Self::UnsupportedContainment => MxcErrorCode::UnsupportedContainment,
59 Self::UnsupportedPhase => MxcErrorCode::UnsupportedPhase,
60 Self::BackendUnavailable => MxcErrorCode::BackendUnavailable,
61 Self::MalformedId => MxcErrorCode::MalformedId,
62 Self::StaleId => MxcErrorCode::StaleId,
63 Self::NotProvisioned => MxcErrorCode::NotProvisioned,
64 Self::NotStarted => MxcErrorCode::NotStarted,
65 Self::AlreadyStarted => MxcErrorCode::AlreadyStarted,
66 Self::AlreadyStopped => MxcErrorCode::AlreadyStopped,
67 Self::PolicyValidation => MxcErrorCode::PolicyValidation,
68 Self::BackendError => MxcErrorCode::BackendError,
69 }
70 }
71}
72
73impl From<MxcErrorCode> for ErrorCode {
74 fn from(code: MxcErrorCode) -> Self {
75 match code {
76 MxcErrorCode::MalformedRequest => Self::MalformedRequest,
77 MxcErrorCode::UnsupportedContainment => Self::UnsupportedContainment,
78 MxcErrorCode::UnsupportedPhase => Self::UnsupportedPhase,
79 MxcErrorCode::BackendUnavailable => Self::BackendUnavailable,
80 MxcErrorCode::MalformedId => Self::MalformedId,
81 MxcErrorCode::StaleId => Self::StaleId,
82 MxcErrorCode::NotProvisioned => Self::NotProvisioned,
83 MxcErrorCode::NotStarted => Self::NotStarted,
84 MxcErrorCode::AlreadyStarted => Self::AlreadyStarted,
85 MxcErrorCode::AlreadyStopped => Self::AlreadyStopped,
86 MxcErrorCode::PolicyValidation => Self::PolicyValidation,
87 MxcErrorCode::BackendError => Self::BackendError,
88 }
89 }
90}
91
92#[derive(Clone, PartialEq, Eq)]
102#[non_exhaustive]
103pub struct Error {
104 pub code: ErrorCode,
106 pub message: String,
108 pub operation: Option<String>,
112 pub native_code: Option<String>,
115 pub remediation: Option<String>,
117 pub details: Option<Box<serde_json::Value>>,
120}
121
122impl std::fmt::Debug for Error {
123 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
124 f.debug_struct("Error")
125 .field("code", &self.code)
126 .field("message", &self.message)
127 .field("operation", &self.operation)
128 .field("native_code", &self.native_code)
129 .field("remediation", &self.remediation)
130 .field("details", &self.details.as_ref().map(|_| "<redacted>"))
131 .finish()
132 }
133}
134
135impl Error {
136 pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
139 Self {
140 code,
141 message: message.into(),
142 operation: None,
143 native_code: None,
144 remediation: None,
145 details: None,
146 }
147 }
148}
149
150impl std::fmt::Display for Error {
154 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155 write!(f, "{}: {}", self.code, self.message)?;
156 if let Some(operation) = &self.operation {
157 write!(f, " [{operation}")?;
158 if let Some(native_code) = &self.native_code {
159 write!(f, " {native_code}")?;
160 }
161 write!(f, "]")?;
162 }
163 Ok(())
164 }
165}
166
167impl std::error::Error for Error {}
168
169impl From<MxcError> for Error {
170 fn from(error: MxcError) -> Self {
171 let (operation, native_code) = match error.api_failure {
172 Some(failure) => {
173 let failure = *failure;
174 (Some(failure.operation), failure.native_code)
175 }
176 None => (None, None),
177 };
178 Self {
179 code: error.code.into(),
180 message: error.message,
181 operation,
182 native_code,
183 remediation: error.remediation,
184 details: error.details.map(Box::new),
185 }
186 }
187}
188
189impl Error {
190 #[doc(hidden)]
199 pub fn into_mxc_error(self) -> MxcError {
200 let mut error = MxcError::new(self.code.to_internal(), self.message);
201 if let Some(operation) = self.operation {
202 let mut failure = ApiFailure::new(operation);
203 failure.native_code = self.native_code;
204 error = error.with_api_failure(failure);
205 }
206 if let Some(remediation) = self.remediation {
207 error = error.with_remediation(remediation);
208 }
209 error.details = self.details.map(|details| *details);
210 error
211 }
212}
213
214#[cfg(test)]
215mod tests {
216 use super::*;
217 use crate::mxc_common::mxc_error::{ApiFailure as InnerFailure, MxcError};
218 use crate::mxc_common::policy_failures::PolicyFailures;
219
220 #[test]
221 fn policy_failures_error_debug_does_not_render_structured_resources() {
222 let payload =
223 serde_json::json!({ "policyFailures": { "resource": "POLICY_RESOURCE_MARKER" } });
224 let inner = MxcError::backend_error("Creation refused.").with_details(payload);
225 assert!(!format!("{inner:?}").contains("POLICY_RESOURCE_MARKER"));
226 let error = Error::from(inner);
227 assert!(!format!("{error:?}").contains("POLICY_RESOURCE_MARKER"));
228 assert!(error
229 .details
230 .as_deref()
231 .unwrap()
232 .get("policyFailures")
233 .is_some());
234 }
235
236 #[test]
237 fn policy_failures_details_survive_sdk_conversions() {
238 let payload = serde_json::json!({ "policyFailures": PolicyFailures::default() });
239 let original = MxcError::backend_error("Creation refused.").with_details(payload.clone());
240 let converted = Error::from(original);
241 assert_eq!(converted.details.as_deref(), Some(&payload));
242 assert_eq!(converted.into_mxc_error().details, Some(payload));
243 assert!(std::mem::size_of::<Error>() < 128);
244 }
245
246 #[test]
254 fn the_conversion_preserves_the_api_detail() {
255 let inner = MxcError::backend_error("The provision was not found.")
256 .with_details(serde_json::json!({"backend": "test"}))
257 .with_api_failure(
258 InnerFailure::new("IsoSessionOps.StopSessionAsync").with_native_code("0x80070490"),
259 )
260 .with_remediation("Provision the session first.");
261
262 let error = Error::from(inner);
263
264 assert_eq!(error.code, ErrorCode::BackendError);
265 assert_eq!(error.message, "The provision was not found.");
266 assert_eq!(
267 error.details,
268 Some(Box::new(serde_json::json!({"backend": "test"})))
269 );
270 assert_eq!(
271 error.operation.as_deref(),
272 Some("IsoSessionOps.StopSessionAsync")
273 );
274 assert_eq!(error.native_code.as_deref(), Some("0x80070490"));
275 assert_eq!(
276 error.remediation.as_deref(),
277 Some("Provision the session first.")
278 );
279 }
280
281 #[test]
285 fn an_operation_without_a_status_leaves_the_rest_absent() {
286 let error = Error::from(
287 MxcError::backend_error("boom").with_api_failure(InnerFailure::new("Iface.Call")),
288 );
289
290 assert_eq!(error.operation.as_deref(), Some("Iface.Call"));
291 assert_eq!(error.native_code, None);
292 assert_eq!(error.remediation, None);
293 }
294
295 #[test]
298 fn an_error_raised_before_any_api_call_carries_no_detail() {
299 let converted = Error::from(MxcError::malformed_request("bad json"));
300
301 assert_eq!(converted.operation, None);
302 assert_eq!(converted.native_code, None);
303 assert_eq!(converted.remediation, None);
304 assert_eq!(converted.details, None);
305
306 let constructed = Error::new(ErrorCode::BackendError, "x");
307
308 assert_eq!(constructed.operation, None);
309 assert_eq!(constructed.native_code, None);
310 assert_eq!(constructed.remediation, None);
311 assert_eq!(constructed.details, None);
312 }
313
314 #[test]
315 fn the_conversion_round_trip_preserves_details() {
316 let inner = MxcError::backend_error("boom")
317 .with_details(serde_json::json!({"phase": "wait"}))
318 .with_api_failure(InnerFailure::new("Iface.Wait").with_native_code("0x80004005"))
319 .with_remediation("Retry.");
320
321 assert_eq!(Error::from(inner.clone()).into_mxc_error(), inner);
322 }
323
324 #[test]
328 fn a_remediation_without_an_operation_renders_without_brackets() {
329 let error = Error::from(
330 MxcError::policy_validation("unsupported policy")
331 .with_remediation("Supply a supported policy."),
332 );
333
334 assert_eq!(error.operation, None);
335 assert_eq!(
336 error.remediation.as_deref(),
337 Some("Supply a supported policy.")
338 );
339 assert_eq!(error.to_string(), "policy_validation: unsupported policy");
340 }
341
342 #[test]
345 fn display_keeps_the_operation_and_status_visible() {
346 let with_status = Error::from(
347 MxcError::backend_error("The provision was not found.").with_api_failure(
348 InnerFailure::new("IsoSessionOps.StopSessionAsync").with_native_code("0x80070490"),
349 ),
350 );
351 assert_eq!(
352 with_status.to_string(),
353 "backend_error: The provision was not found. \
354 [IsoSessionOps.StopSessionAsync 0x80070490]"
355 );
356
357 let without_status = Error::from(
360 MxcError::backend_error("nope").with_api_failure(InnerFailure::new("Iface.Call")),
361 );
362 assert_eq!(
363 without_status.to_string(),
364 "backend_error: nope [Iface.Call]"
365 );
366
367 assert_eq!(
369 Error::from(MxcError::malformed_request("bad")).to_string(),
370 "malformed_request: bad"
371 );
372 }
373}