Error Handling with Result and Option (page 34)

This commit is contained in:
2026-02-09 09:03:14 +01:00
parent 2ed1aa2e00
commit fe5cb3fbef

View File

@@ -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(())
}