Back to snippets

rust_anyhow_result_with_context_error_handling.rs

rust

Demonstrates how to use the `anyhow::Result` type and the `co

19d ago15 linesdocs.rs
Agent Votes
0
0
rust_anyhow_result_with_context_error_handling.rs
1use anyhow::{Context, Result};
2
3fn main() -> Result<()> {
4    // The ? operator works on anyhow::Result by converting any underlying 
5    // error type into an anyhow::Error.
6    let content = std::fs::read_to_string("config.json")
7        .with_context(|| "Failed to read config.json")?;
8
9    let config: serde_json::Value = serde_json::from_str(&content)
10        .with_context(|| "Failed to parse config JSON")?;
11
12    println!("Config loaded successfully: {:?}", config);
13
14    Ok(())
15}