Skip to content

Instantly share code, notes, and snippets.

@TomerCohen95
Last active October 5, 2023 08:43
Show Gist options
  • Save TomerCohen95/40bd61cf9f3e26a212f07fc865286271 to your computer and use it in GitHub Desktop.
Save TomerCohen95/40bd61cf9f3e26a212f07fc865286271 to your computer and use it in GitHub Desktop.
use anyhow::{Context};
use std::fs::File;
use std::io::{Read};
fn read_file_contents(path: &str) -> tomercode_error::Result<String> {
let contents = open_file(path).with_context(|| format!("Failed to open file: {}", path))?;
let processed_contents = process_contents(&contents).context("could not process file contents")?;
Ok(processed_contents)
}
fn open_file(path: &str) -> anyhow::Result<String> {
let mut file = File::open(path).context("could not open file")?;
let mut contents = String::new();
file.read_to_string(&mut contents).with_context(|| format!("Failed to read file: {}", path))?;
Ok(contents)
}
fn process_contents(contents: &str) -> tomercode_error::Result<String> {
// Simulate processing logic (e.g., parsing, transformation)
if contents.contains("error") {
return Err(TomerCodeError::InvalidState(anyhow::anyhow!("Processing error: 'error' found in contents")));
}
Ok(contents.to_owned())
}
fn main() {
let file_path = "file.txt";
read_file_contents(file_path).context("failed to read file contents").unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment