Error Handling with Result and Option (page 31)
This commit is contained in:
22
src/main.rs
22
src/main.rs
@@ -1,5 +1,6 @@
|
||||
use clap::{Parser, Subcommand};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
@@ -32,6 +33,27 @@ struct TodoList {
|
||||
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 {
|
||||
fn new() -> Self {
|
||||
TodoList {
|
||||
|
||||
Reference in New Issue
Block a user