skip to content

You lead a Rust workspace with a storage crate, a domain crate and a web service binary: what error strategy do you set across the crates, and where do errors convert?

level: principalimportance: should knowfreq 30%

answer

  1. typed where other code calls in
  2. variants only for caller decisions
  3. wrap dependency errors, don't expose them
  4. one boundary type in the binary
  5. convert once, report once

basics

~20 s

Library crates return thiserror enums whose variants are the failures callers act on, wrapping dependency errors instead of exposing them. The binary uses anyhow internally and converts everything at one boundary type that decides the response.

solid answer

~50 s

My default is typed errors below and opaque errors at the top. The storage crate returns a thiserror enum with only the variants callers act on, `NotFound` and `Conflict`, plus a `Backend` variant whose source is the driver's error boxed as `Box<dyn std::error::Error + Send + Sync>`, so the driver's type never appears in our public API and our semver stays our own. The domain crate is the judgment call: typed if more than one consumer branches on its failures, `anyhow::Result` if it only reports. In the binary, handlers return one `ApiError` with `#[from]` for each library error and `#[error(transparent)] Other(#[from] anyhow::Error)`, so `?` works everywhere and a single `match` maps variants to status codes. Errors are logged once, at that boundary. For a crate with outside consumers I'd add `#[non_exhaustive]` or an opaque struct.

code

rust · 60 lines
rust
mod storage {
    // Library crate: a typed error whose variants are the contract.
    #[derive(Debug, thiserror::Error)]
    pub enum StorageError {
        #[error("record {id} not found")]
        NotFound { id: u64 },
        #[error("record {id} was modified concurrently")]
        Conflict { id: u64 },
        #[error("storage backend failed")]
        Backend(#[source] std::io::Error),
    }

    pub fn load(id: u64) -> Result<String, StorageError> {
        match id {
            1 => Ok("alice".into()),
            2 => Err(StorageError::Conflict { id }),
            3 => Err(StorageError::Backend(std::io::Error::other("disk gone"))),
            _ => Err(StorageError::NotFound { id }),
        }
    }
}

// Binary: one boundary type that decides the response.
#[derive(Debug, thiserror::Error)]
enum ApiError {
    #[error(transparent)]
    Storage(#[from] storage::StorageError),
    #[error(transparent)]
    Other(#[from] anyhow::Error),
}

impl ApiError {
    fn status(&self) -> u16 {
        use storage::StorageError::*;
        match self {
            ApiError::Storage(NotFound { .. }) => 404,
            ApiError::Storage(Conflict { .. }) => 409,
            ApiError::Storage(Backend(_)) | ApiError::Other(_) => 500,
        }
    }
}

fn render(name: &str) -> anyhow::Result<String> {
    anyhow::ensure!(!name.is_empty(), "empty name");
    Ok(format!("<h1>{name}</h1>"))
}

fn get_user(id: u64) -> Result<String, ApiError> {
    let name = storage::load(id)?; // StorageError -> ApiError::Storage
    Ok(render(&name)?) // anyhow::Error -> ApiError::Other
}

fn main() {
    for id in 1..=4 {
        match get_user(id) {
            Ok(page) => println!("{id}: 200 {page}"),
            Err(e) => println!("{id}: {} {e}", e.status()),
        }
    }
}

go deeper

for a junior

Recall the overall shape: library crates return their own typed errors, and the application uses one catch-all error type at the top.

for a middle

Explain how #[from] lifts one crate's error into the next layer's type, so ? works across crate boundaries without map_err.

for a senior

Show where the conversions sit in a real service: branch on typed variants at the boundary, use a transparent catch-all for anyhow errors, and log once.

for a principal

Own the tradeoffs: how many variants each crate should carry, how to keep dependency types out of public APIs, when a middle crate earns a typed error, and how to write the policy down.

## The default: typed below, opaque above A workspace usually layers its crates: a **storage** crate that talks to a database, a **domain** crate with the business rules, and a **web service binary** that wires them together. The error strategy follows from who reads each crate's errors: - **Library crates** are called by other code, which may need to *act* on a failure (return 404, retry, ask the user again). They return typed errors, usually enums derived with thiserror. - **The binary** mostly *reports* failures. Inside it, `anyhow::Result` keeps propagation cheap. - **Conversion happens at the seams.** `#[from]` lifts a lower crate's error into the next layer's type, and one boundary type in the binary decides the response. There is no single right answer here, because each choice trades caller precision against maintenance cost. A lead's job is to pick defaults and write down the exceptions. ## Designing a library crate's error surface - **Variants follow caller decisions, not causes.** `NotFound` and `Conflict` exist because the web layer answers 404 and 409. A dozen distinct database failures that all mean "the backend broke" collapse into one `Backend` variant. - **Wrap dependency errors, don't expose them.** A public variant like `Db(#[from] DriverError)` makes the driver a public dependency. The API Guidelines (C-STABLE) say a crate "cannot be stable (>=1.0.0) without all of its public dependencies being stable", and upgrading the driver's major version becomes a breaking change for your crate. Keep the driver error as a private source, for example inside a boxed `dyn Error`, and expose only what callers need. - **Plan for growth.** Adding a variant to a public enum breaks exhaustive matches downstream. `#[non_exhaustive]` and opaque error structs are the tools for that, covered in the material on API evolution. thiserror's README shows the opaque form: a public `#[error(transparent)] struct PublicError(#[from] ErrorRepr)` over a private enum, with accessor methods. - **Implement the std traits.** The derive gives you `std::error::Error`, and keeping fields `Send + Sync + 'static` lets the error cross threads and convert into `anyhow::Error`. ## The middle crates are a real judgment call | Domain crate's errors | Choose when | Cost | |---|---|---| | its own thiserror enum | several consumers, or tests that assert on failure kinds | a type to maintain, plus conversions at both seams | | `anyhow::Result` | only the binary consumes it, and it only reports | callers must downcast to branch, and the compiler cannot check that | | re-exporting the storage enum | the domain layer is a thin pass-through | the domain API now changes whenever storage's does | A useful test: if anyone writes `downcast_ref` on this crate's errors, the crate wanted a typed error. ## The binary's boundary 1. Handlers return `Result<T, ApiError>`, where `ApiError` has `Storage(#[from] StorageError)` and `#[error(transparent)] Other(#[from] anyhow::Error)`. 2. `?` lifts typed library errors into their variants, and lifts anything from anyhow-based helpers into `Other`. 3. One method, such as `status()`, matches on `ApiError` and picks the response. Turning that into a framework response type belongs with each web framework's own error handling. 4. The error is logged **once**, at this boundary, with its cause chain. Adding context and choosing log formats belong with the material on context and backtraces. ```rust fn get_user(id: u64) -> Result<String, ApiError> { let name = storage::load(id)?; // StorageError -> ApiError::Storage Ok(render(&name)?) // anyhow::Error -> ApiError::Other } ``` ## Anti-patterns to rule out - **One workspace-wide error enum.** Every crate's callers see variants their crate can never produce, matches carry dead arms, and every crate depends on the crate that holds the enum. - **`anyhow::Result` in every public function** of a library with several callers. Branching then turns into a set of runtime downcasts nobody can see in a signature. - **A variant per dependency**: `Io`, `Json`, `Db`, `Http`. That mirrors the implementation instead of the decisions callers make, and leaks every dependency into the API. - **Logging at every layer**, so one failure shows up as five log lines. ## What to write down as team policy 1. Library crates expose thiserror enums or opaque structs; public functions never return `anyhow::Result`. 2. Variants exist only for failures some caller handles differently; everything else goes in a catch-all. 3. No third-party error type appears in a public signature without an explicit decision. 4. Binaries use anyhow internally and convert at one boundary type. 5. Errors are logged once, where they are handled.

  • Should the whole workspace share one error enum?
    Not as a default. A shared enum shows every crate's callers variants their crate can never produce, so matches carry arms that can never fire, and adding a variant for one crate touches all of them. Per-crate enums joined with `#[from]` at the seams keep each surface honest. The cost is a little conversion code.
  • When would you expose an opaque error struct instead of a public enum?
    When outside consumers depend on the crate and its failure kinds are still changing. thiserror's README shows the pattern: a public `#[error(transparent)] struct PublicError(#[from] ErrorRepr)` over a private enum that can change across minor versions, with accessor methods for what callers may ask. The cost is that callers ask through methods instead of matching.
  • What is wrong with a public `Db(#[from] DriverError)` variant in the storage crate?
    The driver becomes a public dependency. Its type is in your API, so moving to its next major version is a breaking change for every caller of yours. The API Guidelines also say a crate cannot be stable unless its public dependencies are. Keep the driver error as a private source and expose only the variants callers act on.

  • Every crate should return anyhow::Result so error handling looks uniform.
  • Each library should expose one variant per underlying dependency error.
  • Re-exporting a driver's error type in a public variant has no semver cost.
  • One workspace-wide error enum is the simplest choice for every crate.
  • The binary should log the same error at every layer it passes through.