imag/libimagstore/src/error.rs

113 lines
2.1 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;
#[derive(Clone)]
pub enum StoreErrorType {
IdNotFound,
OutOfMemory,
// maybe more
}
impl From<StoreErrorType> for String {
fn from(e: StoreErrorType) -> String {
String::from(&e)
}
}
impl<'a> From<&'a StoreErrorType> for String {
fn from(e: &'a StoreErrorType) -> String {
match e {
&StoreErrorType::IdNotFound => String::from("ID not found"),
&StoreErrorType::OutOfMemory => String::from("Out of Memory"),
}
}
}
impl Debug for StoreErrorType {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
let s : String = self.into();
try!(write!(fmt, "{:?}", s));
Ok(())
}
}
impl Display for StoreErrorType {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
let s : String = self.into();
try!(write!(fmt, "{}", s));
Ok(())
}
}
2016-01-12 17:51:13 +00:00
pub struct StoreError {
err_type: StoreErrorType,
2016-01-16 12:39:53 +00:00
expl: &'static str,
2016-01-12 17:51:13 +00:00
cause: Option<Box<Error>>,
}
impl StoreError {
2016-01-16 12:39:53 +00:00
pub fn new(errtype: StoreErrorType, expl: &'static str, cause: Option<Box<Error>>)
-> StoreError
{
2016-01-12 17:51:13 +00:00
StoreError {
2016-01-16 12:39:53 +00:00
err_type: errtype,
expl: expl,
cause: cause,
2016-01-12 17:51:13 +00:00
}
}
pub fn err_type(&self) -> StoreErrorType {
self.err_type.clone()
}
2016-01-12 17:51:13 +00:00
}
impl Debug for StoreError {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
try!(write!(fmt, "[{:?}]: {:?}, caused: {:?}",
self.err_type, self.expl, self.cause));
2016-01-12 17:51:13 +00:00
Ok(())
}
}
impl Display for StoreError {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
let e : String = self.err_type.clone().into();
2016-01-16 12:39:53 +00:00
try!(write!(fmt, "[{}]: {}", e, self.expl));
2016-01-12 17:51:13 +00:00
Ok(())
}
}
impl Error for StoreError {
fn description(&self) -> &str {
2016-01-16 12:39:53 +00:00
self.expl
2016-01-12 17:51:13 +00:00
}
fn cause(&self) -> Option<&Error> {
self.cause.as_ref().map(|e| &**e)
}
}