Skip to main content

volga_di/
error.rs

1//! Describes dependency injection errors
2
3use std::fmt::{Display, Formatter};
4
5/// Describes dependency injection error
6#[derive(Debug, Clone, Copy)]
7pub enum Error {
8    /// Indicates that the DI container is missing or not configured
9    ContainerMissing,
10
11    /// Indicates that the DI container couldn't resolve a service
12    ResolveFailed(&'static str),
13
14    /// Indicates that a requests service has not been registered in the DI container
15    NotRegistered(&'static str),
16
17    /// Indicates any other error
18    Other(&'static str)
19}
20
21impl Display for Error {
22    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
23        match self { 
24            Error::ContainerMissing => write!(f, "Services Error: DI container is missing"),
25            Error::ResolveFailed(type_name) => write!(f, "Services Error: unable to resolve the service: {type_name}"),
26            Error::NotRegistered(type_name) => write!(f, "Services Error: service not registered: {type_name}"),
27            Error::Other(msg) => write!(f, "{msg}"),
28        }
29    }
30}
31
32#[cfg(test)]
33mod tests {
34    use super::*;
35
36    #[test]
37    fn it_displays_container_missing() {
38        assert_eq!(
39            format!("{}", Error::ContainerMissing), 
40            "Services Error: DI container is missing"
41        );
42    }
43
44    #[test]
45    fn it_displays_resolve_failed() {
46        assert_eq!(
47            format!("{}", Error::ResolveFailed("Type")), 
48            "Services Error: unable to resolve the service: Type"
49        );
50    }
51
52    #[test]
53    fn it_displays_not_registered() {
54        assert_eq!(
55            format!("{}", Error::NotRegistered("Type")), 
56            "Services Error: service not registered: Type"
57        );
58    }
59
60    #[test]
61    fn it_displays_other() {
62        assert_eq!(
63            format!("{}", Error::Other("some error")), 
64            "some error"
65        );
66    }
67}