use thiserror::Error;
#[derive(Debug, Error)]
pub enum MappingError {
#[error("Failure while serializing mapping data: {0}")]
InputDataError(#[from] serde_json::Error),
#[error("Failure while constructing statement: {0}")]
BuildError(String),
#[error("Failure while collecting statement arguments: {0}")]
ArgumentError(String),
#[error("Could not map row to requested type")]
InputRowError(#[from] sqlx::Error),
}
#[derive(Debug, Error)]
pub enum RepositoryError {
#[error("Could not find a matching database entry")]
DatabaseLookupError(),
#[error("Database error: {0}")]
DatabaseError(sqlx::Error),
#[error("SQL Statement Error: {0}")]
SqlStatementError(#[from] MappingError),
#[error("Repository failure: {0}")]
GenericRepositoryError(&'static str),
}
impl From<sqlx::Error> for RepositoryError {
fn from(value: sqlx::Error) -> Self {
match value {
sqlx::Error::RowNotFound => Self::DatabaseLookupError(),
_ => RepositoryError::DatabaseError(value),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_sqlx_error_to_repository_error_conversion() {
let repo_err = RepositoryError::from(sqlx::Error::RowNotFound);
assert_eq!(
repo_err.to_string(),
"Could not find a matching database entry".to_owned()
);
}
#[test]
fn test_mapping_error_to_repository_error_conversion() {
let repo_err = RepositoryError::from(MappingError::BuildError("Test".to_owned()));
assert_eq!(
repo_err.to_string(),
"SQL Statement Error: Failure while constructing statement: Test"
)
}
}