Use the anyhow crate to simplify error handling by returning anyhow::Result<T> instead of Result<T, E> and propagating errors with the ? operator. Add anyhow = "1" to your Cargo.toml dependencies, import anyhow::Result and the anyhow! macro, then define functions to return Result types that automatically convert other errors.
use anyhow::{anyhow, Result};
fn read_config() -> Result<String> {
let content = std::fs::read_to_string("config.txt")?;
if content.is_empty() {
return Err(anyhow!("Config file is empty"));
}
Ok(content)
}
fn main() -> Result<()> {
let config = read_config()?;
println!("Config: {}", config);
Ok(())
}