Skip to content

Instantly share code, notes, and snippets.

@nielsle
Created October 14, 2014 12:56
Show Gist options
  • Select an option

  • Save nielsle/1cdf928250b251488e61 to your computer and use it in GitHub Desktop.

Select an option

Save nielsle/1cdf928250b251488e61 to your computer and use it in GitHub Desktop.
Error chaining with enums
// Library code
trait Error {
fn kind(&self) -> &ErrorKind;
}
trait ErrorKind {
fn cause(&self) -> Option<&Error>;
}
#[deriving(Show)]
pub struct WrappedError<K> {
pub description: String,
pub detail: Option<String>,
pub kind: K,
}
impl <K: ErrorKind> Error for WrappedError<K> {
fn kind(&self) -> &ErrorKind { &self.kind as &ErrorKind }
}
// Application code
pub type AError = WrappedError<AErrorKind>;
#[deriving(Show)]
pub enum AErrorKind { Excuses, MoreExcuses, }
impl ErrorKind for AErrorKind {
fn cause(&self) -> Option<&Error> { None }
}
pub type MyError = WrappedError<MyErrorKind>;
#[deriving(Show)]
pub enum MyErrorKind { CausedByA(AError), CausedByMe, }
// This is boiler plate. Could rust derive this?
impl ErrorKind for MyErrorKind {
fn cause(&self) -> Option<&Error> {
match *self {
CausedByA(ref error) => Some(error as &Error),
CausedByMe => None,
}
}
}
fn main() {
let a_error =
WrappedError{description: "A".to_string(),
detail: None,
kind: Excuses,};
let my_error =
WrappedError{description: "My".to_string(),
detail: None,
kind: CausedByA(a_error),};
print!("{}" , my_error);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment