Skip to main content

cool_error_from_sqlx

Function cool_error_from_sqlx 

Source
pub fn cool_error_from_sqlx(error: Error) -> CoolError
Expand description

Convert a sqlx::Error to CoolError, preserving structured database error information when available.

§When a typed variant is produced

If error is sqlx::Error::Database(db_err), this function produces CoolError::DatabaseTyped with the SQLSTATE code and constraint name extracted from the driver error. All other sqlx::Error kinds (pool timeouts, decode errors, etc.) fall back to CoolError::Database with the stringified message, identical to the legacy error.to_string() path.

§Usage

use cratestack_sqlx::cool_error_from_sqlx;

sqlx::query("INSERT …")
    .execute(&pool)
    .await
    .map_err(cool_error_from_sqlx)?;

Consumers can then inspect the error:

if err.db_sqlstate() == Some("23505") {
    let constraint = err.db_constraint(); // e.g. "accounts_email_key"
}