Error Handling with Result and Option (page 31)

This commit is contained in:
2026-02-05 11:14:17 +01:00
parent 835b66e708
commit 4c77d74985

View File

@@ -1,5 +1,6 @@
use clap::{Parser, Subcommand}; use clap::{Parser, Subcommand};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::fmt;
use std::fs; use std::fs;
use std::path::Path; use std::path::Path;
@@ -32,6 +33,27 @@ struct TodoList {
next_id: usize, next_id: usize,
} }
#[derive(Debug)]
enum TodoError {
FileError(String),
ParseError(String),
TaskNotFound(usize),
InvalidInput(String),
}
impl fmt::Display for TodoError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
TodoError::FileError(msg) => write!(f, "File error: {}", msg),
TodoError::ParseError(msg) => write!(f, "Parse error: {}", msg),
TodoError::TaskNotFound(id) => write!(f, "Task {} not found", id),
TodoError::InvalidInput(msg) => write!(f, "Invalid input: {}", msg),
}
}
}
impl std::error::Error for TodoError {}
impl TodoList { impl TodoList {
fn new() -> Self { fn new() -> Self {
TodoList { TodoList {