db_core/common/
errors.rs

1//! Error codes and related functions
2//!
3
4
5use std;
6
7/// Error representation.
8#[derive(Debug)]
9pub struct Error {
10    kind: ErrorKind,
11    repr: ErrorRepr
12}
13
14
15impl Error {
16
17    fn new(kind: ErrorKind, repr: ErrorRepr) -> Error {
18        Error {
19            kind,
20            repr
21        }
22    }
23
24    /// Returns kind of error.
25    pub fn kind(&self) -> ErrorKind {
26        self.kind
27    }
28}
29
30
31impl std::error::Error for Error { }
32
33
34macro_rules! gen_error_kinds {
35    ( $($kind:ident, $msg:literal), *) => {
36        #[derive(Debug, PartialEq, Copy, Clone)]
37        /// Types of errors.
38        pub enum ErrorKind {
39            $(
40                $kind,
41            )*
42        }
43
44        impl Error {
45            /// Returns string description of a error.
46            pub fn str_desc(&self) -> &str {
47                match self.kind {
48                    $(
49                        ErrorKind::$kind => $msg,
50                    )*
51                }
52            }
53        }
54    };
55}
56
57
58macro_rules! gen_create_fun {
59    ( $($kind:ident, $create_fun:ident), *) => {
60        impl Error {
61            $(
62                /// Create an error of a given type.
63                #[inline]
64                pub fn $create_fun() -> Self {
65                    Self::new(ErrorKind::$kind, ErrorRepr::Simple)
66                }
67            )*
68        }
69    };
70
71    ( $($kind:ident, $create_fun:ident, $fun_arg:path), *) => {
72        impl Error {
73            $(
74                /// Create an error of a given type.
75                #[inline]
76                pub fn $create_fun(e: $fun_arg) -> Self {
77                    Self::new(ErrorKind::$kind, ErrorRepr::$kind(e))
78                }
79            )*
80        }
81    }
82}
83
84
85macro_rules! gen_error_repr {
86    ($( $from_type:ty, $error_kind:ident, $fun_name:ident ), *) => {
87
88        #[derive(Debug)]
89        enum ErrorRepr {
90            Simple,
91            $(
92                $error_kind($from_type),
93            )*
94        }
95
96        $(
97            impl From<$from_type> for Error {
98                fn from(error: $from_type) -> Self {
99                    Error::new(ErrorKind::$error_kind, ErrorRepr::$error_kind(error))
100                }
101            }
102        )*
103
104        impl std::fmt::Display for Error {
105            fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
106                write!(f, "{}", self.str_desc())?;
107                match &self.repr {
108                    $(
109                        ErrorRepr::$error_kind(e) => write!(f, ": {}", e),
110                    )*
111                    _ => Ok(())
112                }?;
113        
114                Ok(())
115            }
116        }
117
118        impl Error {
119        
120            $(
121                pub fn $fun_name(self) -> Option<$from_type> {
122                    match self.repr {
123                        ErrorRepr::$error_kind(e) => Some(e),
124                        _ => None
125                    }
126                }
127            )*
128        }
129
130    };
131}
132
133
134gen_error_kinds![
135    NoError                         , "no error",
136    NotImplemented                  , "not implemented",
137    IoError                         , "io error",
138    IncorrectAllocationSize         , "incorrect allocation size",
139    PathIsTooLong                   , "path is too long",
140    Utf8ValidationError             , "utf-8 validation error",
141    AllocationFailure               , "allocation failure",
142    IncorrectLayout                 , "incorrect layout",
143    ArrayIsFull                     , "array is full",
144    MagicMismatch                   , "magic mismatch", 
145    DataFileNotInitialized          , "data file was not properly initialized",
146    SliceConversionError            , "unexpected conversion failure",
147    LockError                       , "lock failure",
148    FailedToBuildPath               , "failed to build path",
149    FileIdOverflow                  , "overflow of file_id for data files",
150    ExtentLimitReached              , "data file extent limit reached",
151    IncorrectExtentSize             , "incorrect extent size (less than minimum size, or greater than maximum size)",
152    IncorrectBlockSize              , "incorrect block size (less than minimum size, or greater than maximum size, or not is power of two)",
153    IncorrectExtentSettings         , "initial extent number is too small or greater than the maximum allowed number of extents",
154    LoggerIsTerminated              , "logger is terminated",
155    StringParseError                , "string parse error",
156    FileNotOpened                   , "file is not opened",
157    ExtentDoesNotExist              , "extent with specified id does not exist",
158    FileDoesNotExist                , "file with specified id does not exist",
159    BlockDoesNotExist               , "block with specified id does not exist",
160    ObjectDoesNotExist              , "object with specified id does not exist",
161    ObjectIsDeleted                 , "object with specified id was deleted",
162    UnexpectedCheckpoint            , "unexpected checkpoint record appeared while reading transaction log",
163    BlockChecksumMismatch           , "block checksum mismatch",
164    TimeOperationError              , "internal error while performing operation on time value",
165    DbSizeLimitReached              , "configured database size limits have been reached, can't add more data",
166    TryLockError                    , "lock operation was not successful",
167    BlockCrcMismatch                , "crc cehcksum failed for block",
168    Timeout                         , "operations timed out",
169    CheckpointStoreSizeLimitReached , "checkpoint store size limit reached"
170];
171
172
173gen_create_fun![
174    NoError                         , no_error                      , 
175    NotImplemented                  , not_implemented               , 
176    IncorrectAllocationSize         , incorrect_allocation_size     , 
177    PathIsTooLong                   , path_is_too_long              , 
178    AllocationFailure               , allocation_failure            , 
179    ArrayIsFull                     , array_is_full                 , 
180    MagicMismatch                   , magic_mismatch                , 
181    DataFileNotInitialized          , data_file_not_initialized     , 
182    LockError                       , lock_error                    , 
183    FailedToBuildPath               , failed_to_build_path          , 
184    FileIdOverflow                  , file_id_overflow              , 
185    ExtentLimitReached              , extent_limit_reached          , 
186    IncorrectExtentSize             , incorrect_extent_size         , 
187    IncorrectBlockSize              , incorrect_block_size          ,  
188    IncorrectExtentSettings         , incorrect_extent_settings     ,
189    LoggerIsTerminated              , logger_is_terminated          ,
190    FileNotOpened                   , file_not_opened               , 
191    ExtentDoesNotExist              , extent_does_not_exist         ,
192    FileDoesNotExist                , file_does_not_exist           ,
193    BlockDoesNotExist               , block_does_not_exist          ,
194    ObjectDoesNotExist              , object_does_not_exist         ,
195    ObjectIsDeleted                 , object_is_deleted             ,
196    UnexpectedCheckpoint            , unexpected_checkpoint         ,
197    BlockChecksumMismatch           , block_checksum_mismatch       ,
198    DbSizeLimitReached              , db_size_limit_reached         ,
199    TryLockError                    , try_lock_error                ,
200    BlockCrcMismatch                , block_crc_mismatch            ,
201    Timeout                         , timeout,
202    CheckpointStoreSizeLimitReached , checkpoint_store_size_limit_reached
203];
204
205
206gen_create_fun![
207    IoError                     , io_error                      , std::io::Error,
208    Utf8ValidationError         , utf8_validation_error         , std::str::Utf8Error,
209    IncorrectLayout             , incorrect_layout              , std::alloc::LayoutErr,
210    SliceConversionError        , slice_conversion_error        , std::array::TryFromSliceError,
211    StringParseError            , string_parse_error            , std::num::ParseIntError,
212    TimeOperationError          , time_operation_error          , std::time::SystemTimeError
213];
214
215
216gen_error_repr![
217    std::io::Error, IoError, io_err,
218    std::str::Utf8Error, Utf8ValidationError, utf8_err,
219    std::alloc::LayoutErr, IncorrectLayout, layout_err,
220    std::array::TryFromSliceError, SliceConversionError, slice_err,
221    std::num::ParseIntError, StringParseError, string_parse_err,
222    std::time::SystemTimeError, TimeOperationError, time_operation_err
223];
224