From 508b8269d0d75702414feb87ff8f42a94835aa14 Mon Sep 17 00:00:00 2001 From: Jeff Baskin Date: Fri, 15 Nov 2024 13:37:11 -0500 Subject: [PATCH] Added errprs. --- .gitignore | 2 +- src/data/mod.rs | 4 ++-- src/error.rs | 51 +++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + 4 files changed, 55 insertions(+), 3 deletions(-) create mode 100644 src/error.rs diff --git a/.gitignore b/.gitignore index b2880bf..9c4360c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ /target *.pyc *.swp - +*.swo diff --git a/src/data/mod.rs b/src/data/mod.rs index aa91b1d..fd654d7 100644 --- a/src/data/mod.rs +++ b/src/data/mod.rs @@ -33,7 +33,7 @@ impl Table { None => { self.fields.insert(name.to_string(), FieldDef::new()); Ok(()) - }, + } } } } @@ -61,7 +61,7 @@ mod table { tbl.add_field("one", "id"); match tbl.add_field("one", "id") { Ok(_) => unreachable!(" Should not duplicates."), - Err(_) => {}, + Err(_) => {} } } } diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..5114bc1 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,51 @@ +use std::{error::Error, fmt}; + +#[derive(Debug)] +enum ErrorType { + TableAddFieldDuplicate(String), +} + +impl fmt::Display for ErrorType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ErrorType::TableAddFieldDuplicate(data) => write!(f, "field '{}' already exists", data), + } + } +} + +#[derive(Debug)] +struct MTTError { + err: ErrorType, +} + +impl MTTError { + fn new(err: ErrorType) -> Self { + Self { + err: err, + } + } +} + +impl Error for MTTError {} + +impl fmt::Display for MTTError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.err.to_string()) + } +} + +#[cfg(test)] +mod errors { + use super::*; + + #[test] + fn get_error() { + let err = MTTError::new(ErrorType::TableAddFieldDuplicate("tester".to_string())); + assert_eq!(err.to_string(), "field 'tester' already exists"); + assert!(err.source().is_none()); + let err = MTTError::new(ErrorType::TableAddFieldDuplicate("other".to_string())); + assert_eq!(err.to_string(), "field 'other' already exists"); + assert!(err.source().is_none()); + } +} + diff --git a/src/lib.rs b/src/lib.rs index 51bacf5..69b0131 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,6 @@ mod client; mod data; +mod error; mod message; mod router; mod session;