From 4c77d749855f24904aba32d6b0587297fe170360 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakob=20R=C3=B6nnb=C3=A4ck?= Date: Thu, 5 Feb 2026 11:14:17 +0100 Subject: [PATCH] Error Handling with Result and Option (page 31) --- src/main.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/main.rs b/src/main.rs index ccbbe24..f159129 100644 --- a/src/main.rs +++ b/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 {