morethantext-web/src/morethantext/error.rs

90 lines
1.8 KiB
Rust
Raw Normal View History

2022-09-27 07:31:59 -04:00
use std::{error::Error, fmt};
2022-07-22 20:34:50 -04:00
2023-03-14 11:32:37 -04:00
#[derive(Debug)]
pub enum ErrorCode {
2023-05-29 15:42:32 -04:00
// General
2023-03-14 11:32:37 -04:00
Undefined(String),
}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ErrorCode::Undefined(msg) => write!(f, "{}", msg),
2023-05-29 15:42:32 -04:00
}
}
}
mod errorcodes {
use super::*;
const ITEMS: [&str; 2] = ["one", "two"];
#[test]
fn undefined_display() {
for item in ITEMS {
let err = ErrorCode::Undefined(item.to_string());
assert_eq!(err.to_string(), item);
2023-03-14 11:32:37 -04:00
}
}
}
2022-07-22 20:34:50 -04:00
#[derive(Debug)]
2023-05-29 15:42:32 -04:00
pub struct MTTError {
code: ErrorCode,
2022-07-23 21:28:34 -04:00
}
2023-05-29 15:42:32 -04:00
impl MTTError {
fn new<S>(msg: S) -> Self
2022-08-06 12:03:47 -04:00
where
S: Into<String>,
{
2023-05-29 15:42:32 -04:00
let text = msg.into();
2022-07-22 20:34:50 -04:00
Self {
2023-05-29 15:42:32 -04:00
code: ErrorCode::Undefined(text),
2022-07-22 20:34:50 -04:00
}
}
2022-07-23 21:28:34 -04:00
2023-05-29 15:42:32 -04:00
fn from_code(code: ErrorCode) -> Self {
Self { code: code }
2022-07-23 21:28:34 -04:00
}
2022-07-22 20:34:50 -04:00
}
2023-05-29 15:42:32 -04:00
impl Error for MTTError {}
2022-07-23 21:28:34 -04:00
2023-05-29 15:42:32 -04:00
impl fmt::Display for MTTError {
2022-07-22 20:34:50 -04:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2023-03-14 11:32:37 -04:00
write!(f, "{}", self.code)
2022-07-22 20:34:50 -04:00
}
}
#[cfg(test)]
2023-03-14 11:32:37 -04:00
mod errors {
2022-08-06 12:03:47 -04:00
use super::*;
#[test]
2023-05-29 15:42:32 -04:00
fn create_with_str() {
let msgs = ["one", "two"];
for msg in msgs {
let err = MTTError::new(msg);
assert_eq!(err.to_string(), msg);
2023-03-14 11:32:37 -04:00
}
}
#[test]
2023-05-29 15:42:32 -04:00
fn create_with_string() {
let msg = "three";
let err = MTTError::new(msg.to_string());
assert_eq!(err.to_string(), msg);
2023-03-14 11:32:37 -04:00
}
#[test]
2023-05-29 15:42:32 -04:00
fn create_from_code() {
let code = ErrorCode::Undefined("oops".to_string());
let err = MTTError::from_code(code);
match err.code {
ErrorCode::Undefined(_) => (),
_ => assert!(false, "{:?} is not undefined", err.code),
2023-03-14 11:32:37 -04:00
}
}
}