Rust

Custom Error Type with thiserror

admin by @admin ADMIN
6d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
The `thiserror` crate generates a clean `Error + Display + Debug` impl from an enum, with automatic `From` conversions. The library-author's error-type tool of choice.
Rust
Raw
// Cargo.toml: thiserror = "1"
use thiserror::Error;
use std::io;

#[derive(Error, Debug)]
pub enum AppError {
    #[error("config file not found: {0}")]
    ConfigMissing(String),

    #[error("I/O error: {0}")]
    Io(#[from] io::Error),       // auto-convert from std::io::Error

    #[error("invalid value for {field}: {value}")]
    Invalid { field: String, value: String },
}

fn load(path: &str) -> Result<String, AppError> {
    std::fs::read_to_string(path)?      // io::Error auto-converts to AppError
        .lines().next()
        .map(|s| s.to_string())
        .ok_or_else(|| AppError::ConfigMissing(path.to_string()))
}

fn main() {
    match load("config.toml") {
        Ok(line) => println!("first line: {line}"),
        Err(e)   => eprintln!("error: {e}"),
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.