Error Handling with Result and Option (page 34)
This commit is contained in:
40
src/main.rs
40
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(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user