[Minigrep] - passing the errors to the calling function

This commit is contained in:
adnanioricce 2024-12-28 09:39:14 -03:00
parent d61f038555
commit ecc50583b9

@ -1,6 +1,6 @@
use std::env; use std::env;
use std::error::Error;
use std::fs; use std::fs;
use std::os::unix::process;
struct Config { struct Config {
query: String, query: String,
file_path: String, file_path: String,
@ -15,6 +15,12 @@ impl Config {
Ok(Config { query, file_path }) Ok(Config { query, file_path })
} }
} }
fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
println!("With text:\n {contents}");
Ok(())
}
fn main() { fn main() {
let args: Vec<String> = env::args().collect(); let args: Vec<String> = env::args().collect();
let config = Config::build(&args).unwrap_or_else(|err| { let config = Config::build(&args).unwrap_or_else(|err| {
@ -25,8 +31,8 @@ fn main() {
println!("Searching for {}", config.query); println!("Searching for {}", config.query);
println!("In file {}", config.file_path); println!("In file {}", config.file_path);
let contents = if let Err(e) = run(config) {
fs::read_to_string(config.file_path).expect("Should have been able to read the file"); println!("Application error: {e}");
std::process::exit(1);
println!("With text:\n {contents}"); }
} }