Use anyhow to simplify error handling by returning a generic Result<T, anyhow::Error> type instead of defining custom error enums. Add the crate to your Cargo.toml, import anyhow and Result, and use the anyhow! macro to create errors from strings or the ? operator to propagate them automatically.
use anyhow::{anyhow, Result};
fn read_config() -> Result<String> {
// Propagate errors with ?
let content = std::fs::read_to_string("config.txt")?;
// Create a custom error if needed
if content.is_empty() {
return Err(anyhow!("Config file is empty"));
}
Ok(content)
}
In your Cargo.toml, ensure you have the dependency:
[dependencies]
anyhow = "1"