medi_rs/
error.rs

1use thiserror::Error;
2
3#[derive(Debug, Error)]
4pub enum Error {
5    #[error("Handler not found")]
6    HandlerNotFound,
7
8    #[error("Can not cast to the required type '{0}'")]
9    CastError(String),
10
11    #[error("Handler error {0}")]
12    Handler(Box<dyn std::error::Error + Send + Sync>),
13
14    #[error("Resource not found")]
15    ResourceNotFound,
16
17    #[error("No event handler registered")]
18    NoEventHandlerRegistered,
19
20    #[error("Event Processing Error")]
21    EventProcessingError,
22
23    #[error("Event Publishing Error")]
24    EventPublishingError,
25}
26
27/// Handler result type
28/// This is a wrapper around the result type with the error type as the handler error
29pub type Result<T> = core::result::Result<T, Error>;
30
31impl Error {
32    /// Get the handler error if it is a handler error
33    pub fn get_handler_error<T: std::error::Error + Send + Sync + 'static>(&self) -> Option<&T> {
34        match self {
35            Error::Handler(handler_error) => handler_error.downcast_ref::<T>(),
36            _ => None,
37        }
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    #[derive(Debug, thiserror::Error)]
46    enum TestError {}
47
48    #[test]
49    fn test_get_handler_error_should_return_none() {
50        let error = Error::HandlerNotFound;
51
52        let handler_error = error.get_handler_error::<TestError>();
53
54        assert!(handler_error.is_none());
55    }
56}