actix_storage/
error.rs

1use std::error::Error;
2
3use actix_web::{http::StatusCode, ResponseError};
4use thiserror::Error;
5
6/// Error type that will be returned from all fallible methods of actix_storage.
7///
8/// implementers should generally use Custom variant for their own errors.
9#[derive(Debug, Error)]
10pub enum StorageError {
11    /// Occurs when expiry methods are not available or the implementer doesn't support
12    /// the method.
13    #[error("StorageError: Method not supported for the storage backend provided")]
14    MethodNotSupported,
15    /// Occurs when serialization is not possible, either because of wrong format specified
16    /// or wrong type.
17    #[error("StorageError: Serialization failed")]
18    SerializationError,
19    /// Occurs when deserialization is not possible, either because of wrong format specified
20    /// or wrong type.
21    #[error("StorageError: Deserialization failed")]
22    DeserializationError,
23    /// Occurs when the underlying storage implementer faces error
24    #[error("StorageError: {:?}", self)]
25    Custom(Box<dyn Error + Send>),
26}
27
28impl StorageError {
29    /// Shortcut method to construct Custom variant
30    pub fn custom<E>(err: E) -> Self
31    where
32        E: 'static + Error + Send,
33    {
34        Self::Custom(Box::new(err))
35    }
36}
37
38impl ResponseError for StorageError {
39    fn status_code(&self) -> StatusCode {
40        StatusCode::INTERNAL_SERVER_ERROR
41    }
42}
43
44pub type Result<T> = std::result::Result<T, StorageError>;
45
46#[cfg(test)]
47mod test {
48    use super::*;
49    use thiserror::Error;
50
51    #[derive(Debug, Error)]
52    #[error("My error")]
53    struct MyError;
54
55    #[test]
56    fn test_error() {
57        let e = MyError;
58        let s = StorageError::custom(e);
59        assert!(s.status_code() == StatusCode::INTERNAL_SERVER_ERROR);
60        if let StorageError::Custom(err) = s {
61            assert!(format!("{}", err) == "My error");
62        }
63    }
64}