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