From 95e52197c9779182023df7e1bf48f91e53ef71cc Mon Sep 17 00:00:00 2001 From: David Greenberg Date: Tue, 30 May 2017 13:00:06 -0600 Subject: [PATCH] Extend ResultExt to Option, allow chaining with boxed Errors --- Cargo.toml | 2 +- src/error_chain.rs | 25 +++++++++++++++++++++++-- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 4683bf06a..a6993e5ec 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "error-chain" -version = "0.10.1-pre" +version = "0.10.0" authors = [ "Brian Anderson ", "Paul Colomiets ", "Colin Kiegel ", diff --git a/src/error_chain.rs b/src/error_chain.rs index 266ab0b8d..1d1d28e7d 100644 --- a/src/error_chain.rs +++ b/src/error_chain.rs @@ -137,6 +137,17 @@ macro_rules! error_chain_processed { ) } + /// Construct a chained error from another boxed error and a kind, and generates a backtrace + pub fn with_boxed_chain(error: Box<::std::error::Error + Send>, kind: K) + -> $error_name + where K: Into<$error_kind_name> + { + $error_name( + kind.into(), + $crate::State::new::<$error_name>(error, ), + ) + } + /// Returns the kind of the error. pub fn kind(&self) -> &$error_kind_name { &self.0 @@ -302,7 +313,7 @@ macro_rules! error_chain_processed { // The ResultExt trait defines the `chain_err` method. /// Additional methods for `Result`, for easy interaction with this crate. - pub trait $result_ext_name { + pub trait $result_ext_name { /// If the `Result` is an `Err` then `chain_err` evaluates the closure, /// which returns *some type that can be converted to `ErrorKind`*, boxes /// the original error to store as the cause, then returns a new error @@ -312,7 +323,7 @@ macro_rules! error_chain_processed { EK: Into<$error_kind_name>; } - impl $result_ext_name for ::std::result::Result where E: ::std::error::Error + Send + 'static { + impl $result_ext_name for ::std::result::Result where E: ::std::error::Error + Send + 'static { fn chain_err(self, callback: F) -> ::std::result::Result where F: FnOnce() -> EK, EK: Into<$error_kind_name> { @@ -323,6 +334,16 @@ macro_rules! error_chain_processed { } } + impl $result_ext_name for ::std::option::Option { + fn chain_err(self, callback: F) -> ::std::result::Result + where F: FnOnce() -> EK, + EK: Into<$error_kind_name> { + self.ok_or_else(move || { + $crate::ChainedError::from_kind(callback().into()) + }) + } + } + }; }