reindeer/
error.rs

1use std::fmt;
2
3/// Error kind enum for Reindeer-related errors.
4#[non_exhaustive]
5#[derive(Debug, Clone, Copy)]
6pub enum ErrorKind {
7    /// Something went wrong at the `sled` level.
8    SledError,
9    /// Could not serialize or deserialize an entity
10    SerializationError,
11    /// Any kind of file system error while using the database
12    IOError,
13    /// An integrity constraint has been violated while trying to remove an entity from the database
14    IntegrityError,
15    /// An entity was not found
16    NotFound,
17    /// An entity was used without being registered firts in the database
18    UnregisteredEntity,
19}
20
21/// Error type for `reindeer`
22#[derive(Debug)]
23pub struct Error {
24    error_kind: ErrorKind,
25    message: String,
26}
27
28impl Error {
29    /// Creates a new error from an error kind and a message
30    pub fn new(error_kind: ErrorKind, message: String) -> Error {
31        Error {
32            error_kind,
33            message,
34        }
35    }
36    pub fn kind(&self) -> ErrorKind {
37        self.error_kind
38    }
39}
40
41impl fmt::Display for Error {
42    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
43        write!(
44            f,
45            "Reindeer Error of type {:?} : {}",
46            self.error_kind, &self.message
47        )
48    }
49}
50
51impl std::error::Error for Error {}
52
53/// Type definition to simplify the use of Result everywhere in the library
54pub type Result<T> = std::result::Result<T, Error>;
55
56impl From<std::io::Error> for Error {
57    fn from(source: std::io::Error) -> Self {
58        Error::new(ErrorKind::IOError, source.to_string())
59    }
60}
61
62impl From<sled::Error> for Error {
63    fn from(source: sled::Error) -> Self {
64        Error::new(ErrorKind::SledError, source.to_string())
65    }
66}
67
68impl From<bincode::Error> for Error {
69    fn from(source: bincode::Error) -> Self {
70        Error::new(ErrorKind::SerializationError, source.to_string())
71    }
72}
73
74impl From<serde_json::Error> for Error {
75    fn from(source: serde_json::Error) -> Self {
76        Error::new(ErrorKind::SerializationError, source.to_string())
77    }
78}