imag/libimagrt/src/error.rs

70 lines
1.4 KiB
Rust
Raw Normal View History

2016-01-21 17:42:43 +00:00
use std::error::Error;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Error as FmtError;
2016-03-24 11:29:42 +00:00
use std::io::Error as IOError;
2016-01-21 17:42:43 +00:00
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum RuntimeErrorKind {
Instantiate,
2016-03-24 10:50:26 +00:00
IOError,
ProcessExitFailure,
2016-01-21 17:42:43 +00:00
// more?
}
#[derive(Debug)]
pub struct RuntimeError {
kind: RuntimeErrorKind,
cause: Option<Box<Error>>,
}
impl RuntimeError {
pub fn new(kind: RuntimeErrorKind, cause: Option<Box<Error>>) -> RuntimeError {
RuntimeError {
kind: kind,
cause: cause,
}
}
}
fn runtime_error_kind_as_str(e: &RuntimeErrorKind) -> &'static str {
match e {
2016-03-24 10:50:26 +00:00
&RuntimeErrorKind::Instantiate => "Could not instantiate",
&RuntimeErrorKind::IOError => "IO Error",
&RuntimeErrorKind::ProcessExitFailure => "Process exited with failure",
2016-01-21 17:42:43 +00:00
}
}
impl Display for RuntimeError {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
try!(write!(fmt, "{}", runtime_error_kind_as_str(&self.kind)));
Ok(())
}
}
impl Error for RuntimeError {
fn description(&self) -> &str {
runtime_error_kind_as_str(&self.kind)
}
fn cause(&self) -> Option<&Error> {
self.cause.as_ref().map(|e| &**e)
}
}
2016-03-24 11:29:42 +00:00
impl From<IOError> for RuntimeError {
fn from(ioe: IOError) -> RuntimeError {
RuntimeError::new(RuntimeErrorKind::IOError, Some(Box::new(ioe)))
}
}