Skip to main content

awa_model/
error.rs

1use thiserror::Error;
2
3#[derive(Debug, Error)]
4pub enum AwaError {
5    #[error("job not found: {id}")]
6    JobNotFound { id: i64 },
7
8    #[error("callback not found: {callback_id}")]
9    CallbackNotFound { callback_id: String },
10
11    #[error("unique conflict")]
12    UniqueConflict { constraint: Option<String> },
13
14    #[error("schema not migrated: expected version {expected}, found {found}")]
15    SchemaNotMigrated { expected: i32, found: i32 },
16
17    #[error("unknown job kind: {kind}")]
18    UnknownJobKind { kind: String },
19
20    #[error("validation error: {0}")]
21    Validation(String),
22
23    #[error("serialization error: {0}")]
24    Serialization(#[from] serde_json::Error),
25
26    #[error("database error: {0}")]
27    Database(#[source] sqlx::Error),
28
29    #[cfg(feature = "tokio-postgres")]
30    #[error("tokio-postgres error: {0}")]
31    TokioPg(#[source] tokio_postgres::Error),
32}
33
34impl From<sqlx::Error> for AwaError {
35    fn from(err: sqlx::Error) -> Self {
36        AwaError::Database(err)
37    }
38}
39
40/// The single Rust-side mapping from a raw `sqlx::Error` to an [`AwaError`],
41/// translating a Postgres unique violation (SQLSTATE 23505) into
42/// [`AwaError::UniqueConflict`] with the offending constraint name.
43///
44/// Insert paths call this explicitly rather than relying on the blanket
45/// `From<sqlx::Error>` (which preserves the raw error for general `?` use).
46/// Database adapters running Awa's insert SQL through another driver should
47/// route the underlying sqlx error through here so their errors match the
48/// native path.
49pub fn map_sqlx_error(err: sqlx::Error) -> AwaError {
50    if let sqlx::Error::Database(ref db_err) = err {
51        if db_err.code().as_deref() == Some("23505") {
52            return AwaError::UniqueConflict {
53                constraint: db_err.constraint().map(|c| c.to_string()),
54            };
55        }
56    }
57    AwaError::Database(err)
58}