use serde::Serialize;
use serde::ser::SerializeStruct;
use thiserror::Error;
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum CoreError {
#[error("invalid password")]
InvalidPassword,
#[error("invalid password format: {0}")]
InvalidPasswordFormat(String),
#[error("agent is locked; call unlock before signing")]
Locked,
#[error("algorithm mismatch: expected {expected}, got {actual}")]
AlgorithmMismatch {
expected: String,
actual: String,
},
#[error("unsupported algorithm: {0}")]
UnsupportedAlgorithm(String),
#[error("malformed document: {0}")]
MalformedDocument(String),
#[error("malformed key: {0}")]
MalformedKey(String),
#[error("malformed envelope: {0}")]
MalformedEnvelope(String),
#[error("signature invalid: {0}")]
SignatureInvalid(String),
#[error("encryption failed: {0}")]
EncryptionFailed(String),
#[error("decryption failed: {0}")]
DecryptionFailed(String),
#[error("schema invalid: {0}")]
SchemaInvalid(String),
#[error("agreement failed: {0}")]
AgreementFailed(String),
}
impl CoreError {
pub fn code(&self) -> &'static str {
match self {
CoreError::InvalidPassword => "InvalidPassword",
CoreError::InvalidPasswordFormat(_) => "InvalidPasswordFormat",
CoreError::Locked => "Locked",
CoreError::AlgorithmMismatch { .. } => "AlgorithmMismatch",
CoreError::UnsupportedAlgorithm(_) => "UnsupportedAlgorithm",
CoreError::MalformedDocument(_) => "MalformedDocument",
CoreError::MalformedKey(_) => "MalformedKey",
CoreError::MalformedEnvelope(_) => "MalformedEnvelope",
CoreError::SignatureInvalid(_) => "SignatureInvalid",
CoreError::EncryptionFailed(_) => "EncryptionFailed",
CoreError::DecryptionFailed(_) => "DecryptionFailed",
CoreError::SchemaInvalid(_) => "SchemaInvalid",
CoreError::AgreementFailed(_) => "AgreementFailed",
}
}
}
impl Serialize for CoreError {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let details = match self {
CoreError::AlgorithmMismatch { expected, actual } => Some(serde_json::json!({
"expected": expected,
"actual": actual,
})),
_ => None,
};
let mut s =
serializer.serialize_struct("CoreError", if details.is_some() { 3 } else { 2 })?;
s.serialize_field("code", self.code())?;
s.serialize_field("message", &self.to_string())?;
if let Some(d) = details {
s.serialize_field("details", &d)?;
}
s.end()
}
}