use crate::mxc_common::mxc_error::{ApiFailure, MxcError, MxcErrorCode};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ErrorCode {
MalformedRequest,
UnsupportedContainment,
UnsupportedPhase,
BackendUnavailable,
MalformedId,
StaleId,
NotProvisioned,
NotStarted,
AlreadyStarted,
AlreadyStopped,
PolicyValidation,
BackendError,
}
impl ErrorCode {
pub fn as_str(self) -> &'static str {
match self {
Self::MalformedRequest => "malformed_request",
Self::UnsupportedContainment => "unsupported_containment",
Self::UnsupportedPhase => "unsupported_phase",
Self::BackendUnavailable => "backend_unavailable",
Self::MalformedId => "malformed_id",
Self::StaleId => "stale_id",
Self::NotProvisioned => "not_provisioned",
Self::NotStarted => "not_started",
Self::AlreadyStarted => "already_started",
Self::AlreadyStopped => "already_stopped",
Self::PolicyValidation => "policy_validation",
Self::BackendError => "backend_error",
}
}
}
impl std::fmt::Display for ErrorCode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl ErrorCode {
fn to_internal(self) -> MxcErrorCode {
match self {
Self::MalformedRequest => MxcErrorCode::MalformedRequest,
Self::UnsupportedContainment => MxcErrorCode::UnsupportedContainment,
Self::UnsupportedPhase => MxcErrorCode::UnsupportedPhase,
Self::BackendUnavailable => MxcErrorCode::BackendUnavailable,
Self::MalformedId => MxcErrorCode::MalformedId,
Self::StaleId => MxcErrorCode::StaleId,
Self::NotProvisioned => MxcErrorCode::NotProvisioned,
Self::NotStarted => MxcErrorCode::NotStarted,
Self::AlreadyStarted => MxcErrorCode::AlreadyStarted,
Self::AlreadyStopped => MxcErrorCode::AlreadyStopped,
Self::PolicyValidation => MxcErrorCode::PolicyValidation,
Self::BackendError => MxcErrorCode::BackendError,
}
}
}
impl From<MxcErrorCode> for ErrorCode {
fn from(code: MxcErrorCode) -> Self {
match code {
MxcErrorCode::MalformedRequest => Self::MalformedRequest,
MxcErrorCode::UnsupportedContainment => Self::UnsupportedContainment,
MxcErrorCode::UnsupportedPhase => Self::UnsupportedPhase,
MxcErrorCode::BackendUnavailable => Self::BackendUnavailable,
MxcErrorCode::MalformedId => Self::MalformedId,
MxcErrorCode::StaleId => Self::StaleId,
MxcErrorCode::NotProvisioned => Self::NotProvisioned,
MxcErrorCode::NotStarted => Self::NotStarted,
MxcErrorCode::AlreadyStarted => Self::AlreadyStarted,
MxcErrorCode::AlreadyStopped => Self::AlreadyStopped,
MxcErrorCode::PolicyValidation => Self::PolicyValidation,
MxcErrorCode::BackendError => Self::BackendError,
}
}
}
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Error {
pub code: ErrorCode,
pub message: String,
pub operation: Option<String>,
pub native_code: Option<String>,
pub remediation: Option<String>,
pub details: Option<Box<serde_json::Value>>,
}
impl std::fmt::Debug for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Error")
.field("code", &self.code)
.field("message", &self.message)
.field("operation", &self.operation)
.field("native_code", &self.native_code)
.field("remediation", &self.remediation)
.field("details", &self.details.as_ref().map(|_| "<redacted>"))
.finish()
}
}
impl Error {
pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
operation: None,
native_code: None,
remediation: None,
details: None,
}
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.code, self.message)?;
if let Some(operation) = &self.operation {
write!(f, " [{operation}")?;
if let Some(native_code) = &self.native_code {
write!(f, " {native_code}")?;
}
write!(f, "]")?;
}
Ok(())
}
}
impl std::error::Error for Error {}
impl From<MxcError> for Error {
fn from(error: MxcError) -> Self {
let (operation, native_code) = match error.api_failure {
Some(failure) => {
let failure = *failure;
(Some(failure.operation), failure.native_code)
}
None => (None, None),
};
Self {
code: error.code.into(),
message: error.message,
operation,
native_code,
remediation: error.remediation,
details: error.details.map(Box::new),
}
}
}
impl Error {
#[doc(hidden)]
pub fn into_mxc_error(self) -> MxcError {
let mut error = MxcError::new(self.code.to_internal(), self.message);
if let Some(operation) = self.operation {
let mut failure = ApiFailure::new(operation);
failure.native_code = self.native_code;
error = error.with_api_failure(failure);
}
if let Some(remediation) = self.remediation {
error = error.with_remediation(remediation);
}
error.details = self.details.map(|details| *details);
error
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mxc_common::mxc_error::{ApiFailure as InnerFailure, MxcError};
use crate::mxc_common::policy_failures::PolicyFailures;
#[test]
fn policy_failures_error_debug_does_not_render_structured_resources() {
let payload =
serde_json::json!({ "policyFailures": { "resource": "POLICY_RESOURCE_MARKER" } });
let inner = MxcError::backend_error("Creation refused.").with_details(payload);
assert!(!format!("{inner:?}").contains("POLICY_RESOURCE_MARKER"));
let error = Error::from(inner);
assert!(!format!("{error:?}").contains("POLICY_RESOURCE_MARKER"));
assert!(error
.details
.as_deref()
.unwrap()
.get("policyFailures")
.is_some());
}
#[test]
fn policy_failures_details_survive_sdk_conversions() {
let payload = serde_json::json!({ "policyFailures": PolicyFailures::default() });
let original = MxcError::backend_error("Creation refused.").with_details(payload.clone());
let converted = Error::from(original);
assert_eq!(converted.details.as_deref(), Some(&payload));
assert_eq!(converted.into_mxc_error().details, Some(payload));
assert!(std::mem::size_of::<Error>() < 128);
}
#[test]
fn the_conversion_preserves_the_api_detail() {
let inner = MxcError::backend_error("The provision was not found.")
.with_details(serde_json::json!({"backend": "test"}))
.with_api_failure(
InnerFailure::new("IsoSessionOps.StopSessionAsync").with_native_code("0x80070490"),
)
.with_remediation("Provision the session first.");
let error = Error::from(inner);
assert_eq!(error.code, ErrorCode::BackendError);
assert_eq!(error.message, "The provision was not found.");
assert_eq!(
error.details,
Some(Box::new(serde_json::json!({"backend": "test"})))
);
assert_eq!(
error.operation.as_deref(),
Some("IsoSessionOps.StopSessionAsync")
);
assert_eq!(error.native_code.as_deref(), Some("0x80070490"));
assert_eq!(
error.remediation.as_deref(),
Some("Provision the session first.")
);
}
#[test]
fn an_operation_without_a_status_leaves_the_rest_absent() {
let error = Error::from(
MxcError::backend_error("boom").with_api_failure(InnerFailure::new("Iface.Call")),
);
assert_eq!(error.operation.as_deref(), Some("Iface.Call"));
assert_eq!(error.native_code, None);
assert_eq!(error.remediation, None);
}
#[test]
fn an_error_raised_before_any_api_call_carries_no_detail() {
let converted = Error::from(MxcError::malformed_request("bad json"));
assert_eq!(converted.operation, None);
assert_eq!(converted.native_code, None);
assert_eq!(converted.remediation, None);
assert_eq!(converted.details, None);
let constructed = Error::new(ErrorCode::BackendError, "x");
assert_eq!(constructed.operation, None);
assert_eq!(constructed.native_code, None);
assert_eq!(constructed.remediation, None);
assert_eq!(constructed.details, None);
}
#[test]
fn the_conversion_round_trip_preserves_details() {
let inner = MxcError::backend_error("boom")
.with_details(serde_json::json!({"phase": "wait"}))
.with_api_failure(InnerFailure::new("Iface.Wait").with_native_code("0x80004005"))
.with_remediation("Retry.");
assert_eq!(Error::from(inner.clone()).into_mxc_error(), inner);
}
#[test]
fn a_remediation_without_an_operation_renders_without_brackets() {
let error = Error::from(
MxcError::policy_validation("unsupported policy")
.with_remediation("Supply a supported policy."),
);
assert_eq!(error.operation, None);
assert_eq!(
error.remediation.as_deref(),
Some("Supply a supported policy.")
);
assert_eq!(error.to_string(), "policy_validation: unsupported policy");
}
#[test]
fn display_keeps_the_operation_and_status_visible() {
let with_status = Error::from(
MxcError::backend_error("The provision was not found.").with_api_failure(
InnerFailure::new("IsoSessionOps.StopSessionAsync").with_native_code("0x80070490"),
),
);
assert_eq!(
with_status.to_string(),
"backend_error: The provision was not found. \
[IsoSessionOps.StopSessionAsync 0x80070490]"
);
let without_status = Error::from(
MxcError::backend_error("nope").with_api_failure(InnerFailure::new("Iface.Call")),
);
assert_eq!(
without_status.to_string(),
"backend_error: nope [Iface.Call]"
);
assert_eq!(
Error::from(MxcError::malformed_request("bad")).to_string(),
"malformed_request: bad"
);
}
}