embedded_redis_client/error/
error.rs

1// Look here for an example on how to implement error types: https://doc.rust-lang.org/src/std/io/error.rs.html#42
2use std::error::Error;
3use std::fmt;
4use std::io;
5
6use redis;
7
8#[derive(Debug)]
9pub struct EmbeddedRedisClientError {
10    pub error_type: ErrorType,
11    pub context: String,
12    // source: Option<Box<(dyn error::Error)>>,
13}
14
15#[derive(Debug)]
16pub enum ErrorType {
17    IO(io::Error),
18    Redis(redis::RedisError),
19    ServerTimeout,
20    ServerStartup(Box<EmbeddedRedisClientError>),
21    ServerEnvironment,
22    Other,
23}
24
25impl EmbeddedRedisClientError {
26    pub fn new(error_type: ErrorType, context: String) -> Self {
27        Self {
28            error_type: error_type,
29            context: context,
30        }
31    }
32}
33
34impl Error for EmbeddedRedisClientError {
35    fn source(&self) -> Option<&(dyn Error + 'static)> {
36        match &self.error_type {
37            ErrorType::IO(error) => Some(error),
38            _ => None,
39        }
40    }
41}
42
43impl fmt::Display for EmbeddedRedisClientError {
44    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
45        // REVIEW: is this match useful?
46        match &self.error_type {
47            ErrorType::IO(_err) => writeln!(f, "Context:\n{}", &self.context)?,
48            _ => writeln!(f, "Context:\n{}", &self.context)?,
49        };
50
51        match &self.source() {
52            Some(err) => writeln!(f, "Source error:\n{}", err)?,
53            &None => (),
54        }
55        Ok(())
56    }
57}
58
59impl From<std::io::Error> for EmbeddedRedisClientError {
60    fn from(error: std::io::Error) -> EmbeddedRedisClientError {
61        EmbeddedRedisClientError {
62            error_type: ErrorType::IO(error),
63            context: String::new(),
64        }
65    }
66}
67
68impl From<redis::RedisError> for EmbeddedRedisClientError {
69    fn from(error: redis::RedisError) -> EmbeddedRedisClientError {
70        EmbeddedRedisClientError {
71            error_type: ErrorType::Redis(error),
72            context: String::new(),
73        }
74    }
75}