imag/libimagstore/src/error.rs

87 lines
1.7 KiB
Rust
Raw Normal View History

2016-01-12 17:51:13 +00:00
use std::error::Error;
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Error as FmtError;
use std::clone::Clone;
use std::convert::From;
2016-01-12 17:51:13 +00:00
use std::io::Error as IOError;
2016-01-16 13:26:29 +00:00
#[derive(Clone, Copy, Debug)]
pub enum StoreErrorKind {
IdNotFound,
OutOfMemory,
// maybe more
}
fn store_error_type_as_str(e: &StoreErrorKind) -> &'static str {
match e {
&StoreErrorKind::IdNotFound => "ID not found",
&StoreErrorKind::OutOfMemory => "Out of Memory",
}
}
impl Display for StoreErrorKind {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
try!(write!(fmt, "{}", store_error_type_as_str(self)));
Ok(())
}
}
2016-01-12 17:51:13 +00:00
pub struct StoreError {
err_type: StoreErrorKind,
2016-01-12 17:51:13 +00:00
cause: Option<Box<Error>>,
}
impl StoreError {
pub fn new(errtype: StoreErrorKind, cause: Option<Box<Error>>)
2016-01-16 12:39:53 +00:00
-> StoreError
{
2016-01-12 17:51:13 +00:00
StoreError {
2016-01-16 12:39:53 +00:00
err_type: errtype,
cause: cause,
2016-01-12 17:51:13 +00:00
}
}
pub fn err_type(&self) -> StoreErrorKind {
self.err_type.clone()
}
2016-01-12 17:51:13 +00:00
}
impl Debug for StoreError {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
2016-01-16 13:08:39 +00:00
try!(write!(fmt, "[{:?}]: caused by: {:?}",
self.err_type, self.cause));
2016-01-12 17:51:13 +00:00
Ok(())
}
}
impl Display for StoreError {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
2016-01-16 13:08:39 +00:00
try!(write!(fmt, "[{}]", store_error_type_as_str(&self.err_type.clone())));
2016-01-12 17:51:13 +00:00
Ok(())
}
}
impl Error for StoreError {
fn description(&self) -> &str {
2016-01-16 13:08:39 +00:00
store_error_type_as_str(&self.err_type.clone())
2016-01-12 17:51:13 +00:00
}
fn cause(&self) -> Option<&Error> {
self.cause.as_ref().map(|e| &**e)
}
}