redis_cell/
error.rs

1use std;
2use std::error;
3use std::fmt;
4
5#[derive(Debug)]
6pub enum CellError {
7    Generic(GenericError),
8    FromUtf8(std::string::FromUtf8Error),
9    ParseInt(std::num::ParseIntError),
10}
11
12impl CellError {
13    pub fn generic(message: &str) -> CellError {
14        CellError::Generic(GenericError::new(message))
15    }
16}
17
18impl From<std::string::FromUtf8Error> for CellError {
19    fn from(err: std::string::FromUtf8Error) -> CellError {
20        CellError::FromUtf8(err)
21    }
22}
23
24impl From<std::num::ParseIntError> for CellError {
25    fn from(err: std::num::ParseIntError) -> CellError {
26        CellError::ParseInt(err)
27    }
28}
29
30impl fmt::Display for CellError {
31    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
32        match *self {
33            // Both underlying errors already impl `Display`, so we defer to
34            // their implementations.
35            CellError::Generic(ref err) => write!(f, "{}", err),
36            CellError::FromUtf8(ref err) => write!(f, "{}", err),
37            CellError::ParseInt(ref err) => write!(f, "{}", err),
38        }
39    }
40}
41
42impl error::Error for CellError {
43    fn description(&self) -> &str {
44        // Both underlying errors already impl `Error`, so we defer to their
45        // implementations.
46        match *self {
47            CellError::Generic(ref err) => err.description(),
48            CellError::FromUtf8(ref err) => err.description(),
49            CellError::ParseInt(ref err) => err.description(),
50        }
51    }
52
53    fn cause(&self) -> Option<&error::Error> {
54        match *self {
55            // N.B. Both of these implicitly cast `err` from their concrete
56            // types (either `&io::Error` or `&num::ParseIntError`)
57            // to a trait object `&Error`. This works because both error types
58            // implement `Error`.
59            CellError::Generic(ref err) => Some(err),
60            CellError::FromUtf8(ref err) => Some(err),
61            CellError::ParseInt(ref err) => Some(err),
62        }
63    }
64}
65
66#[derive(Debug)]
67pub struct GenericError {
68    message: String,
69}
70
71impl GenericError {
72    pub fn new(message: &str) -> GenericError {
73        GenericError {
74            message: String::from(message),
75        }
76    }
77}
78
79impl<'a> fmt::Display for GenericError {
80    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
81        write!(f, "Store error: {}", self.message)
82    }
83}
84
85impl<'a> error::Error for GenericError {
86    fn description(&self) -> &str {
87        self.message.as_str()
88    }
89
90    fn cause(&self) -> Option<&error::Error> {
91        None
92    }
93}