Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Errors & HTTP Status

Zyvor has a typed error enum

#![allow(unused)]
fn main() {
pub enum Error {
    Database(sqlx::Error),
    NotFound { entity: &'static str, id: i64 },
    UniqueViolation { entity: &'static str, field: &'static str, value: String },
    ForeignKeyViolation { entity: &'static str, field: &'static str, referenced_entity: &'static str },
    Migration(MigrationError),
    Generation(String),
}

pub type Result<T> = std::result::Result<T, Error>;
}

Error implements Display and std::error::Error, with source() chaining to the underlying sqlx::Error where one exists.

Automatic classification

impl From<sqlx::Error> for Error inspects the PostgreSQL SQLSTATE code:

CodeBecomes
23505Error::UniqueViolation { .. }
23503Error::ForeignKeyViolation { .. }
RowNotFoundError::NotFound { .. }
anything elseError::Database(err)

So you don’t parse error strings yourself. CRUD methods already return zyvor::error::Result, which means classification has happened by the time you get the error.

Which method returns which error

MethodError type
create, update, delete, create_many, update_many, delete_manyzyvor::Error
Query::all, count, fetch_allsqlx::Error

Queries return the raw sqlx error. Convert it yourself when you want classification:

#![allow(unused)]
fn main() {
let users = User::find()
    .all(&pool).await
    .map_err(zyvor::Error::from)?;   // ← now it's classified
}

That one .map_err gives you the same typed error on the query path.

Matching instead of string scanning

#![allow(unused)]
fn main() {
use zyvor::Error;

fn to_status(e: Error) -> StatusCode {
    match e {
        Error::NotFound { .. }            => StatusCode::NOT_FOUND,      // 404
        Error::UniqueViolation { .. }     => StatusCode::CONFLICT,       // 409
        Error::ForeignKeyViolation { .. } => StatusCode::BAD_REQUEST,    // 400
        Error::Database(sqlx::Error::RowNotFound) => StatusCode::NOT_FOUND,
        other => {
            eprintln!("DB error: {other}");
            StatusCode::INTERNAL_SERVER_ERROR                            // 500
        }
    }
}
}

Usage in a handler:

#![allow(unused)]
fn main() {
let user = User::create(&state.db, input).await.map_err(to_status)?;
}

This is strictly better than scanning a formatted string for "23505".

⚠️ Don’t trust the payload fields yet

The variants exist and classify correctly, but some fields are placeholders:

FieldReality
NotFound.entityalways "unknown"
NotFound.idalways -1
ForeignKeyViolation.referenced_entityalways "unknown"
UniqueViolation.valuethe full PostgreSQL message, not the duplicate value

And the parsed entity / field come from splitting the constraint name, which breaks on multi-word table names:

ConstraintParsed fieldCorrect field
users_email_keyemail✅
user_profiles_user_id_keyid❌ should be user_id
post_tags_post_id_tag_id_keyid❌ composite

Practical guidance for 0.1: match on the variant to pick a status code. Don’t build user-facing messages from entity / field — write your own message per endpoint instead:

#![allow(unused)]
fn main() {
Error::UniqueViolation { .. } => (
    StatusCode::CONFLICT,
    Json(json!({ "error": "That email is already registered." })),
),
}

You know which endpoint you’re in; the error doesn’t need to tell you.

Not-found behaves differently per operation

OperationMissing row
updateErr(Error::NotFound) — matchable
deleteOk(0)
find().all()Ok(vec![])

So update maps cleanly to 404 through your matcher. For delete and find, 404 is your decision:

#![allow(unused)]
fn main() {
if User::delete(&state.db, id).await.map_err(to_status)? == 0 {
    return Err(StatusCode::NOT_FOUND);
}
}

Migration errors

#![allow(unused)]
fn main() {
pub enum MigrationError {
    FileNotFound(String),
    DriftDetected { migration: String, expected_checksum: String, actual_checksum: String },
    AlreadyAppliedDifferent(String),
    ExecutionFailed { migration: String, source: sqlx::Error },
    TrackingTableFailed(sqlx::Error),
}
}

Note: the CLI currently reports migration failures through its own error type with formatted messages, so you’ll see these as text output rather than as matchable variants. Unifying the two error systems is on the roadmap.

Verified behaviour

CaseRequestResult
Row doesn’t existGET /users/99999✅ 404
Delete missing rowDELETE /users/99999✅ 404
Duplicate unique emailPOST /users, existing email✅ 409
Malformed bodyPOST /users, {"invalid":true}✅ 422

The 422 comes from Axum’s Json extractor failing to deserialize into UserCreate — Zyvor never sees the request. Required fields are enforced by the type system at the boundary, which is exactly where you want it.

Known issue: memory leak on classified errors

From<sqlx::Error> uses Box::leak to turn parsed Strings into the &'static str fields the enum declares. Every UniqueViolation and ForeignKeyViolation permanently leaks two small allocations.

In a long-running server receiving repeated constraint violations, this is unbounded growth. It’s small per occurrence, but it never gets freed.

If you’re running a high-traffic service on 0.1, be aware of it. The fix (changing those fields to String) is planned for 0.2.0.

Known issue: Generation used for runtime validation

Two runtime input errors are reported as Error::Generation, which is otherwise meant for code-generation failures:

  • "UPDATE requires at least one field" — every update field was None
  • "All insert_many items must have the same columns" — mismatched bulk inputs

If you match exhaustively, route these to 400 rather than 500:

#![allow(unused)]
fn main() {
Error::Generation(msg) if msg.contains("at least one field") => StatusCode::BAD_REQUEST,
}

A dedicated InvalidInput variant is planned.