1use thiserror::Error;
2
3#[derive(Debug, Error)]
4pub enum OrmError {
5 #[error("Record not found")]
6 NotFound,
7
8 #[error("Database error: {0}")]
9 Database(#[from] sqlx::Error),
10
11 #[error("Validation failed: {0}")]
12 Validation(String),
13
14 #[error("Forbidden: {0}")]
15 Forbidden(String),
16
17 #[error("Unique constraint violation on field `{field}`")]
18 UniqueViolation { field: String },
19
20 #[error("Foreign key violation: {0}")]
21 ForeignKeyViolation(String),
22
23 #[error("Encryption error: {0}")]
24 Encryption(String),
25
26 #[error("Decryption error: {0}")]
27 Decryption(String),
28
29 #[error("Hashing error: {0}")]
30 Hashing(String),
31
32 #[error("Type conversion error: {0}")]
33 TypeConversion(String),
34
35 #[error("Migration error: {0}")]
36 Migration(String),
37
38 #[error("Configuration error: {0}")]
39 Config(String),
40
41 #[error("Transaction error: {0}")]
42 Transaction(String),
43
44 #[error("Pool timeout")]
45 PoolTimeout,
46
47 #[error("Serialization error: {0}")]
48 Serialization(#[from] serde_json::Error),
49
50 #[error("{0}")]
51 Custom(String),
52}
53
54impl OrmError {
55 pub fn from_sqlx(err: sqlx::Error) -> Self {
57 if let sqlx::Error::Database(ref db_err) = err {
58 let msg = db_err.message();
59 if db_err.code().as_deref() == Some("23505") {
61 let field = db_err.constraint().unwrap_or("unknown").to_string();
63 return OrmError::UniqueViolation { field };
64 }
65 if db_err.code().as_deref() == Some("23503") {
67 return OrmError::ForeignKeyViolation(msg.to_string());
68 }
69 }
70 OrmError::Database(err)
71 }
72}
73
74pub type OrmResult<T> = Result<T, OrmError>;