data_model/
error.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use std::error::Error as StdError;

#[derive(Debug)]
/// Represents a user validation error
pub enum UserValidationError {
    EmailInvalid,
    IdMissing,
    UsernameMissing,
    PasswordMissing
}

#[derive(Debug)]
/// Represents a data model error
pub enum Error {
    MazeValidation(String),
    Serialization(serde_json::Error),
    UserValidation(UserValidationError),
}

impl From<serde_json::Error> for Error {
    fn from(error: serde_json::Error) -> Self {
        Error::Serialization(error)
    }
}

impl std::fmt::Display for UserValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match *self {
            UserValidationError::EmailInvalid => write!(f, "Invalid email address"),
            UserValidationError::IdMissing => write!(f, "No id provided for the user"),
            UserValidationError::UsernameMissing => write!(f, "No username provided for the user"),
            UserValidationError::PasswordMissing => write!(f, "No password provided for the user"),
        }
    }
}


impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match *self {
            Error::MazeValidation(ref message) => write!(f, "{}", message),
            Error::Serialization(ref error) => write!(f, "{}", error),
            Error::UserValidation(ref error) => write!(f, "{}", error),
        }
    }
}

impl StdError for Error {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            Error::MazeValidation(_) => None,
            Error::Serialization(err) => Some(err),
            Error::UserValidation(_) => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn can_create_new_maze_validation_error() {
        let msg = "This is a maze validation error";
        let err = Error::MazeValidation(msg.to_string());
        assert_eq!(format!("{}", err), msg);
    }

    #[test]
    fn can_create_new_user_validation_error() {
        let expected = "Invalid email address";
        let err = Error::UserValidation(UserValidationError::EmailInvalid);
        assert_eq!(format!("{}", err), expected);
    }
}