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
use std::error::Error;

use actix_web::{http::StatusCode, ResponseError};
use thiserror::Error;

/// Error type that will be returned from all fallible methods of actix_storage.
///
/// implementers should generally use Custom variant for their own errors.
#[derive(Debug, Error)]
pub enum StorageError {
    /// Occurs when expiry methods are not available or the implementer doesn't support
    /// the method.
    #[error("StorageError: Method not supported for the storage backend provided")]
    MethodNotSupported,
    /// Occurs when serialization is not possible, either because of wrong format specified
    /// or wrong type.
    #[error("StorageError: Serialization failed")]
    SerializationError,
    /// Occurs when deserialization is not possible, either because of wrong format specified
    /// or wrong type.
    #[error("StorageError: Deserialization failed")]
    DeserializationError,
    /// Occurs when the underlying storage implementer faces error
    #[error("StorageError: {:?}", self)]
    Custom(Box<dyn Error + Send>),
}

impl StorageError {
    /// Shortcut method to construct Custom variant
    pub fn custom<E>(err: E) -> Self
    where
        E: 'static + Error + Send,
    {
        Self::Custom(Box::new(err))
    }
}

impl ResponseError for StorageError {
    fn status_code(&self) -> StatusCode {
        StatusCode::INTERNAL_SERVER_ERROR
    }
}

pub type Result<T> = std::result::Result<T, StorageError>;

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

    #[derive(Debug, Error)]
    #[error("My error")]
    struct MyError;

    #[test]
    fn test_error() {
        let e = MyError;
        let s = StorageError::custom(e);
        assert!(s.status_code() == StatusCode::INTERNAL_SERVER_ERROR);
        if let StorageError::Custom(err) = s {
            assert!(format!("{}", err) == "My error");
        }
    }
}