use std::error::Error;
use std::fmt;
use crate::error::InternalError;
#[derive(Debug)]
pub enum KeyStoreError {
OperationError {
context: String,
source: Box<dyn Error>,
},
QueryError {
context: String,
source: Box<dyn Error>,
},
StorageError {
context: String,
source: Option<Box<dyn Error>>,
},
ConnectionError(Box<dyn Error>),
NotFoundError(String),
DuplicateKeyError(String),
UserDoesNotExistError(String),
InternalError(InternalError),
}
impl Error for KeyStoreError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
KeyStoreError::OperationError { source, .. } => Some(&**source),
KeyStoreError::QueryError { source, .. } => Some(&**source),
KeyStoreError::StorageError {
source: Some(source),
..
} => Some(&**source),
KeyStoreError::StorageError { source: None, .. } => None,
KeyStoreError::ConnectionError(err) => Some(&**err),
KeyStoreError::NotFoundError(_) => None,
KeyStoreError::DuplicateKeyError(_) => None,
KeyStoreError::UserDoesNotExistError(_) => None,
KeyStoreError::InternalError(err) => Some(err),
}
}
}
impl fmt::Display for KeyStoreError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
KeyStoreError::OperationError { context, source } => {
write!(f, "failed to perform operation: {}: {}", context, source)
}
KeyStoreError::QueryError { context, source } => {
write!(f, "failed query: {}: {}", context, source)
}
KeyStoreError::StorageError {
context,
source: Some(source),
} => write!(
f,
"the underlying storage returned an error: {}: {}",
context, source
),
KeyStoreError::StorageError {
context,
source: None,
} => write!(f, "the underlying storage returned an error: {}", context),
KeyStoreError::ConnectionError(err) => {
write!(f, "failed to connect to underlying storage: {}", err)
}
KeyStoreError::NotFoundError(msg) => write!(f, "key not found: {}", msg),
KeyStoreError::DuplicateKeyError(msg) => write!(f, "key already exists: {}", msg),
KeyStoreError::UserDoesNotExistError(msg) => write!(f, "user does not exist: {}", msg),
KeyStoreError::InternalError(err) => f.write_str(&err.to_string()),
}
}
}
#[cfg(feature = "diesel")]
impl From<diesel::r2d2::PoolError> for KeyStoreError {
fn from(err: diesel::r2d2::PoolError) -> KeyStoreError {
KeyStoreError::ConnectionError(Box::new(err))
}
}
impl From<InternalError> for KeyStoreError {
fn from(err: InternalError) -> Self {
Self::InternalError(err)
}
}