Skip to content
rusthacks.dev
Architecture

Error Boundaries Between Layers in a Rust Application

Each layer of an application should speak its own error type. Convert at the boundary with From, keep causes for logs and map to HTTP codes only at the edge.

2 min read
Summarize in AI
Flat illustration for the post “Error Boundaries Between Layers in a Rust Application”, composed around architecture.

When a database constraint fails, three different people care: the developer reading logs wants the SQLSTATE, the domain wants to know the email is taken, and the client wants a 409 with a sentence. One error type cannot serve all three without leaking. The cure is translation at each boundary, once, with From. This post shows the pattern with three layers. It extends error handling in Rust and lives in organizing Rust projects.

Rust 1.90, thiserror 2.

Three layers, three types

rust
// infrastructure: knows the database
#[derive(Debug, thiserror::Error)]
pub enum StoreError {
    #[error("unique constraint {0} violated")]
    Unique(String),
    #[error("database unavailable")]
    Unavailable(#[source] sqlx::Error),
}

// domain: knows the business
#[derive(Debug, thiserror::Error)]
pub enum SignupError {
    #[error("that email is already registered")]
    EmailTaken,
    #[error("signup is temporarily unavailable")]
    Unavailable(#[source] StoreError),
}

// web: knows HTTP
pub struct ApiError {
    pub status: u16,
    pub message: String,
}

Each type uses the words of its layer. StoreError never reaches a client, and ApiError is never constructed in the domain.

Convert at the edges

rust
impl From<StoreError> for SignupError {
    fn from(e: StoreError) -> Self {
        match e {
            StoreError::Unique(c) if c == "users_email_key" => SignupError::EmailTaken,
            other => SignupError::Unavailable(other),
        }
    }
}

impl From<SignupError> for ApiError {
    fn from(e: SignupError) -> Self {
        match e {
            SignupError::EmailTaken => ApiError { status: 409, message: e.to_string() },
            SignupError::Unavailable(_) => ApiError { status: 503, message: e.to_string() },
        }
    }
}

The domain's function returns Result<User, SignupError> and uses ? on repository calls; From converts. The handler returns Result<_, ApiError> and uses ? on the domain call. The one interesting decision, which constraint means "email taken", is made in exactly one match.

Logs get the chain

Because Unavailable keeps the source, logging with {:#} (with anyhow) or walking Error::source() shows signup is temporarily unavailable: database unavailable: connection refused. Log once, at the edge where the response is built, not in every layer. Logging and returning produces the same error five times.

Mistakes

  • A shared AppError enum with a variant per database error, per HTTP error and per domain error. Every layer then imports the lot.
  • Exposing sqlx::Error through the domain trait, which makes the domain depend on the driver and every test double return driver errors.
  • Mapping to HTTP statuses in the domain.
  • Dropping the source and losing the real cause.

Where to relax

In a small service with three handlers, one error enum is simpler and honest. Split when the layers genuinely diverge. In the web layer, Axum error handling shows how to make the final type an IntoResponse. The technique is compatible with anyhow versus thiserror: typed inside, anyhow at the very top. The API guidelines on this are in Rust API Guidelines, error types.

Also inRust
Taggedlayers
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.