feat: error type and input check

This commit is contained in:
Ahmet Kaan GÜMÜŞ 2024-12-11 21:28:40 +03:00
parent a93ed4e9aa
commit e34adfddcf
3 changed files with 44 additions and 0 deletions

28
src/error.rs Normal file
View file

@ -0,0 +1,28 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub enum ForumInputError {
ForbiddenCharacter,
ForbiddenString,
EmptyParameter,
}
impl std::fmt::Display for ForumInputError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
&ForumInputError::ForbiddenCharacter => {
write!(f, "Forbidden Character Detected")
}
&ForumInputError::ForbiddenString => {
write!(f, "Forbidden String Detected")
}
&ForumInputError::EmptyParameter => write!(f, "Parameter is Empty"),
}
}
}
impl std::error::Error for ForumInputError {
fn cause(&self) -> Option<&dyn std::error::Error> {
self.source()
}
}

View file

@ -1,4 +1,5 @@
pub mod database; pub mod database;
pub mod error;
pub mod feature; pub mod feature;
pub mod utils; pub mod utils;

View file

@ -1,5 +1,7 @@
use std::{fs::File, io::Read}; use std::{fs::File, io::Read};
use crate::error::ForumInputError;
pub fn naive_toml_parser(file_location: &str) -> (String, Vec<String>) { pub fn naive_toml_parser(file_location: &str) -> (String, Vec<String>) {
let mut toml_file = File::open(file_location).unwrap(); let mut toml_file = File::open(file_location).unwrap();
let mut toml_ingredients = String::default(); let mut toml_ingredients = String::default();
@ -22,3 +24,16 @@ pub fn naive_toml_parser(file_location: &str) -> (String, Vec<String>) {
(header, parsed) (header, parsed)
} }
pub fn input_checker(input: &String) -> Result<String, ForumInputError> {
if input.is_empty() {
Err(ForumInputError::EmptyParameter)
} else {
let input_without_space = input.split(' ').collect::<Vec<_>>().join("");
if input_without_space.chars().all(char::is_alphanumeric) {
Ok(input.to_owned())
} else {
Err(ForumInputError::ForbiddenCharacter)
}
}
}