use std::fmt::Display;
use thiserror::Error;
use wildland_crypto::error::CryptoError;
use crate::catlib_service::error::CatlibError;
use crate::sfo::api::SfoError;
use crate::LssError;
pub trait ErrContext<E, T> {
fn context(self, ctx: impl Display) -> Result<T, E>;
fn format(err: impl Display, ctx: impl Display) -> String {
format!("{ctx}: {err}")
}
}
#[derive(Error, Debug, Clone, PartialEq, Eq)]
#[repr(C)]
pub enum ForestRetrievalError {
#[error(transparent)]
LssError(#[from] LssError),
#[error("Could not create keypair from bytes retrieved from LSS: {0}")]
KeypairParseError(CryptoError),
}
#[derive(Error, Debug, PartialEq, Eq, Clone)]
#[repr(C)]
pub enum CoreXError {
#[error("Cannot create forest identity: {0}")]
CannotCreateForestIdentityError(String),
#[error("Identity read error: {0}")]
IdentityReadError(String),
#[error("LSS Error: {0}: {1}")]
LSSErr(String, LssError),
#[error("Catlib Error: {0}: {1}")]
CatlibErr(String, CatlibError),
#[error("Crypto Error: {0}: {1}")]
CryptoErr(String, CryptoError),
#[error("CoreX error: {0}")]
Generic(String),
#[error("SFO Error: {0}: {1}")]
SfoErr(String, SfoError),
}
impl<T> ErrContext<CoreXError, T> for Result<T, CoreXError> {
fn context(mut self, ctx: impl Display) -> Result<T, CoreXError> {
if let Err(
CoreXError::CannotCreateForestIdentityError(s)
| CoreXError::IdentityReadError(s)
| CoreXError::LSSErr(s, _)
| CoreXError::CatlibErr(s, _)
| CoreXError::CryptoErr(s, _)
| CoreXError::Generic(s)
| CoreXError::SfoErr(s, _),
) = &mut self
{
*s = format!("{ctx}: {s}")
}
self
}
}
impl<T> ErrContext<CoreXError, T> for Result<T, CatlibError> {
fn context(self, ctx: impl Display) -> Result<T, CoreXError> {
self.map_err(|e| CoreXError::CatlibErr(ctx.to_string(), e))
}
}
impl<T> ErrContext<CoreXError, T> for Result<T, CryptoError> {
fn context(self, ctx: impl Display) -> Result<T, CoreXError> {
self.map_err(|e| CoreXError::CryptoErr(ctx.to_string(), e))
}
}
impl<T> ErrContext<CoreXError, T> for Result<T, LssError> {
fn context(self, ctx: impl Display) -> Result<T, CoreXError> {
self.map_err(|e| CoreXError::LSSErr(ctx.to_string(), e))
}
}