kftray_commons/utils/
error.rs

1use std::fmt;
2
3#[derive(Debug)]
4pub enum DbError {
5    ConnectionFailed(String),
6    QueryFailed(String),
7    DataDecodeFailed(String),
8    RecordNotFound(i64),
9    Other(String),
10}
11
12impl fmt::Display for DbError {
13    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
14        match self {
15            DbError::ConnectionFailed(msg) => write!(f, "Database connection failed: {msg}"),
16            DbError::QueryFailed(msg) => write!(f, "Database query failed: {msg}"),
17            DbError::DataDecodeFailed(msg) => write!(f, "Failed to decode data: {msg}"),
18            DbError::RecordNotFound(id) => write!(f, "No record found with id: {id}"),
19            DbError::Other(msg) => write!(f, "{msg}"),
20        }
21    }
22}
23
24impl std::error::Error for DbError {}
25
26impl From<sqlx::Error> for DbError {
27    fn from(error: sqlx::Error) -> Self {
28        match error {
29            sqlx::Error::RowNotFound => DbError::Other("Row not found".to_string()),
30            sqlx::Error::Database(e) => DbError::QueryFailed(e.to_string()),
31            sqlx::Error::PoolClosed => DbError::ConnectionFailed("Pool closed".to_string()),
32            sqlx::Error::PoolTimedOut => DbError::ConnectionFailed("Pool timed out".to_string()),
33            _ => DbError::Other(error.to_string()),
34        }
35    }
36}
37
38impl From<serde_json::Error> for DbError {
39    fn from(error: serde_json::Error) -> Self {
40        DbError::DataDecodeFailed(error.to_string())
41    }
42}