use thiserror::Error;
#[derive(Debug, Error)]
pub enum OpenTdfError {
#[error("Policy error: {0}")]
Policy(#[from] crate::policy::PolicyError),
#[error("Archive error: {0}")]
Archive(#[from] crate::archive::TdfError),
#[error("KAS error: {0}")]
Kas(#[from] opentdf_protocol::KasError),
#[error("Crypto error: {0}")]
Crypto(#[from] opentdf_crypto::EncryptionError),
#[error("HMAC error: {0}")]
Hmac(#[from] opentdf_crypto::hmac::HmacError),
#[error("Key error: {0}")]
Key(#[from] opentdf_crypto::KeyError),
}
impl OpenTdfError {
pub fn is_retryable(&self) -> bool {
match self {
Self::Kas(e) => e.is_retryable(),
Self::Archive(e) => e.is_retryable(),
_ => false,
}
}
pub fn suggestion(&self) -> Option<&str> {
match self {
Self::Kas(e) => e.suggestion(),
Self::Archive(e) => e.suggestion(),
Self::Policy(e) => e.suggestion(),
_ => None,
}
}
pub fn is_policy_error(&self) -> bool {
matches!(self, Self::Policy(_))
}
pub fn is_crypto_error(&self) -> bool {
matches!(self, Self::Crypto(_) | Self::Hmac(_) | Self::Key(_))
}
pub fn is_kas_error(&self) -> bool {
matches!(self, Self::Kas(_))
}
pub fn is_archive_error(&self) -> bool {
matches!(self, Self::Archive(_))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_error_categories() {
let policy_err = OpenTdfError::Policy(crate::policy::PolicyError::InvalidAttribute {
fqn: "test".to_string(),
reason: "test reason".to_string(),
});
assert!(policy_err.is_policy_error());
assert!(!policy_err.is_crypto_error());
assert!(!policy_err.is_kas_error());
assert!(!policy_err.is_archive_error());
let archive_err =
OpenTdfError::Archive(crate::archive::TdfError::MissingRequiredField { field: "test" });
assert!(archive_err.is_archive_error());
assert!(!archive_err.is_policy_error());
}
#[test]
fn test_error_display() {
let err = OpenTdfError::Policy(crate::policy::PolicyError::InvalidAttribute {
fqn: "test".to_string(),
reason: "test reason".to_string(),
});
let msg = err.to_string();
assert!(msg.contains("Policy error"));
}
}