Skip to content
This repository has been archived by the owner on Aug 16, 2021. It is now read-only.

Extend ResultExt to Option, allow chaining with boxed Errors #156

Merged
merged 1 commit into from
Jul 12, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# Unreleased

- [Add a new method for `Error`: `chain_err`.](https://github.com/brson/error-chain/pull/141)
- [Allow `chain_err` to be used on `Option<T>`](https://github.com/brson/error-chain/pull/156)
- [Add support for creating an error chain on boxed trait errors (`Box<Error>`)](https://github.com/brson/error-chain/pull/156)

# 0.10.0

Expand Down
24 changes: 21 additions & 3 deletions src/error_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,18 @@ macro_rules! error_chain_processed {
-> $error_name
where E: ::std::error::Error + Send + 'static,
K: Into<$error_kind_name>
{
$error_name::with_boxed_chain(Box::new(error), kind)
}

/// Construct a chained error from another boxed error and a kind, and generates a backtrace
pub fn with_boxed_chain<K>(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>(Box::new(error), ),
$crate::State::new::<$error_name>(error, ),
)
}

Expand Down Expand Up @@ -302,7 +310,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<T, E> {
pub trait $result_ext_name<T> {
/// 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
Expand All @@ -312,7 +320,7 @@ macro_rules! error_chain_processed {
EK: Into<$error_kind_name>;
}

impl<T, E> $result_ext_name<T, E> for ::std::result::Result<T, E> where E: ::std::error::Error + Send + 'static {
impl<T, E> $result_ext_name<T> for ::std::result::Result<T, E> where E: ::std::error::Error + Send + 'static {
fn chain_err<F, EK>(self, callback: F) -> ::std::result::Result<T, $error_name>
where F: FnOnce() -> EK,
EK: Into<$error_kind_name> {
Expand All @@ -323,6 +331,16 @@ macro_rules! error_chain_processed {
}
}

impl<T> $result_ext_name<T> for ::std::option::Option<T> {
fn chain_err<F, EK>(self, callback: F) -> ::std::result::Result<T, $error_name>
where F: FnOnce() -> EK,
EK: Into<$error_kind_name> {
self.ok_or_else(move || {
$crate::ChainedError::from_kind(callback().into())
})
}
}


};
}
Expand Down