From fe5cb3fbef21e059fd47dcdfb1a5c7273f9fbf17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakob=20R=C3=B6nnb=C3=A4ck?= Date: Mon, 9 Feb 2026 09:03:14 +0100 Subject: [PATCH] Error Handling with Result and Option (page 34) --- src/main.rs | 40 +++++++++++++++++++++++++++------------- 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/src/main.rs b/src/main.rs index 36d3599..6521cdb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -109,18 +109,32 @@ impl TodoList { fn main() { let cli = Cli::parse(); - match cli.command { - Commands::Add { task } => { - println!("Adding task: {}", task); - } - Commands::List => { - println!("Listing tasks"); - } - Commands::Complete { id } => { - println!("Completing task with id: {}", id); - } - Commands::Remove { id } => { - println!("Removing task with id: {}", id); - } + + if let Err(e) = run_command(cli) { + eprintln!("Error: {}", e); + std::process::exit(1); } } + +fn run_command(cli: Cli) -> Result<(), TodoError> { + let mut todo_list = + TodoList::load_from_file("tasks.json").map_err(|e| TodoError::FileError(e.to_string()))?; + + match cli.command { + Commands::Add { task } => { + todo_list.add_task(task)?; + println!("Task added successfully"); + } + Commands::Complete { id } => { + todo_list.complete_task(id)?; + println!("Task {} marked as complete", id); + } + _ => {} // Handle other commands + } + + todo_list + .save_to_file("todo.json") + .map_err(|e| TodoError::FileError(e.to_string()))?; + + Ok(()) +}