use sea_orm::DbErr;
pub type Result<T> = std::result::Result<T, DbError>;
#[derive(Debug, thiserror::Error)]
pub enum DbError {
#[error("{entity} not found: {key}")]
NotFound {
entity: &'static str,
key: String,
},
#[error("conflict: {0}")]
Conflict(String),
#[error("invalid input: {0}")]
InvalidInput(String),
#[error("database error: {0}")]
Database(#[from] DbErr),
}
impl DbError {
pub fn not_found(entity: &'static str, key: impl Into<String>) -> Self {
Self::NotFound {
entity,
key: key.into(),
}
}
pub fn conflict(message: impl Into<String>) -> Self {
Self::Conflict(message.into())
}
pub fn invalid_input(message: impl Into<String>) -> Self {
Self::InvalidInput(message.into())
}
pub fn from_db_err(err: DbErr) -> Self {
let text = err.to_string();
let lower = text.to_ascii_lowercase();
if lower.contains("unique constraint")
|| lower.contains("duplicate key")
|| lower.contains("23505")
{
Self::Conflict(text)
} else if lower.contains("check constraint")
|| lower.contains("foreign key constraint")
|| lower.contains("23514")
|| lower.contains("23503")
{
Self::InvalidInput(text)
} else {
Self::Database(err)
}
}
}