Rustrusterror-handlingthiserrorproduction-ready

Custom Errors with thiserror

Production error handling using thiserror for deriving Error implementations with automatic From conversions and context propagation.


title: "Custom Errors with thiserror" description: "Production error handling using thiserror for deriving Error implementations with automatic From conversions and context propagation." category: "Rust" language: "rust" tags: ["rust", "error-handling", "thiserror", "production-ready"] createdAt: "2025-01-18" updatedAt: "2025-02-08"

Overview

Structured error handling using thiserror for automatic Error trait derivation. Each error variant carries contextual data, and the #[from] attribute enables automatic conversions. Error types expose methods for HTTP mapping, user-safe messages, and retry decisions.

Code

#[derive(Error, Debug)]
pub enum AppError {
    #[error("User '{id}' not found")]
    NotFound { id: String },
 
    #[error("Database error: {0}")]
    Database(#[from] DatabaseError),
}

Notes

  • #[from] generates From implementations enabling the ? operator for automatic conversion
  • #[source] preserves the error chain for .source() traversal without creating From impls
  • #[error(transparent)] delegates both Display and source to the inner error
  • status_code() and user_message() centralize HTTP response mapping
  • is_retryable() helps callers decide whether to retry failed operations