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

Error Taxonomy and Layer Boundaries

Rule

Model errors by caller decisions, convert infrastructure failures at layer boundaries, preserve structured data, and render only at external boundaries.

Why

Errors are control flow and diagnostics. Layered types keep callers independent of implementation details without losing actionable data.

Do

  • Define domain variants for failures callers handle differently.
  • Keep useful fields such as IDs, paths, states, and retry hints structured.
  • Convert database, HTTP, SDK, parser, and I/O failures at the boundary they cross.
  • Keep infrastructure causes as sources rather than public domain variants by default.
  • Preserve internal detail for logs while returning curated safe API or CLI messages.
  • Follow error propagation for sources, context, and rendering.

Avoid

  • Do not create a variant for every low-level failure when callers cannot react differently.
  • Do not expose dependency error types accidentally from domain APIs.
  • Do not transport internal errors as String, Message(String), or Other(String).
  • Do not include secrets or unredacted inputs in error fields.

Library vs Application

Libraries expose typed boundary errors. Applications may erase orchestration errors while retaining typed domain errors wherever code branches.

Example

#![allow(unused)]
fn main() {
#[derive(Debug, thiserror::Error)]
pub enum LoadProfileError {
    #[error("profile {id} was not found")]
    NotFound { id: ProfileId },

    #[error("reading profile {id}")]
    Read {
        id: ProfileId,
        #[source]
        source: std::io::Error,
    },
}
}

NotFound supports caller behavior; Read hides the storage implementation while retaining its cause.

Exceptions

  • Use a coarse variant when callers make one decision and the source carries the detail.
  • Use text-only errors for external contracts that are already rendered projections.