use std::error::Error;
use std::fmt;
use crate::database::error::DatabaseError;
#[derive(Debug)]
pub enum UserStoreError {
OperationError {
context: String,
source: Box<dyn Error>,
},
QueryError {
context: String,
source: Box<dyn Error>,
},
StorageError {
context: String,
source: Box<dyn Error>,
},
ConnectionError(Box<dyn Error>),
NotFoundError(String),
}
impl Error for UserStoreError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
UserStoreError::OperationError { source, .. } => Some(&**source),
UserStoreError::QueryError { source, .. } => Some(&**source),
UserStoreError::StorageError { source, .. } => Some(&**source),
UserStoreError::ConnectionError(err) => Some(&**err),
UserStoreError::NotFoundError(_) => None,
}
}
}
impl fmt::Display for UserStoreError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
UserStoreError::OperationError { context, source } => {
write!(f, "failed to perform operation: {}: {}", context, source)
}
UserStoreError::QueryError { context, source } => {
write!(f, "failed query: {}: {}", context, source)
}
UserStoreError::StorageError { context, source } => write!(
f,
"the underlying storage returned an error: {}: {}",
context, source
),
UserStoreError::ConnectionError(err) => {
write!(f, "failed to connect to underlying storage: {}", err)
}
UserStoreError::NotFoundError(ref s) => write!(f, "User not found: {}", s),
}
}
}
impl From<DatabaseError> for UserStoreError {
fn from(err: DatabaseError) -> UserStoreError {
match err {
DatabaseError::ConnectionError(_) => UserStoreError::ConnectionError(Box::new(err)),
_ => UserStoreError::StorageError {
context: "The database returned an error".to_string(),
source: Box::new(err),
},
}
}
}