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

Commit 0e85f07

Browse files
committed
More general ResultExt.
Related to #62.
1 parent 8058642 commit 0e85f07

File tree

2 files changed

+21
-11
lines changed

2 files changed

+21
-11
lines changed

src/lib.rs

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -379,32 +379,33 @@ pub trait ChainedError: error::Error + Send + 'static {
379379
}
380380

381381
/// Additionnal methods for `Result`, for easy interaction with this crate.
382-
pub trait ResultExt<T, E: ChainedError> {
382+
pub trait ResultExt<T, E, CE: ChainedError> {
383383
/// If the `Result` is an `Err` then `chain_err` evaluates the closure,
384384
/// which returns *some type that can be converted to `ErrorKind`*, boxes
385385
/// the original error to store as the cause, then returns a new error
386386
/// containing the original error.
387-
fn chain_err<F, EK>(self, callback: F) -> Result<T, E>
387+
fn chain_err<F, EK>(self, callback: F) -> Result<T, CE>
388388
where F: FnOnce() -> EK,
389-
EK: Into<E::ErrorKind>;
389+
EK: Into<CE::ErrorKind>;
390390
}
391391

392-
impl<T, E> ResultExt<T, E> for Result<T, E> where E: ChainedError {
393-
fn chain_err<F, EK>(self, callback: F) -> Result<T, E>
392+
impl<T, E, CE> ResultExt<T, E, CE> for Result<T, E> where CE: ChainedError, E: Into<CE> {
393+
fn chain_err<F, EK>(self, callback: F) -> Result<T, CE>
394394
where F: FnOnce() -> EK,
395-
EK: Into<E::ErrorKind> {
395+
EK: Into<CE::ErrorKind> {
396396
self.map_err(move |e| {
397+
let e = e.into();
397398
#[cfg(feature = "backtrace")]
398399
let error = {
399-
let backtrace = E::extract_backtrace(&e)
400+
let backtrace = CE::extract_backtrace(&e)
400401
.unwrap_or_else(make_backtrace);
401-
E::new(callback().into(), State {
402+
CE::new(callback().into(), State {
402403
next_error: Some(Box::new(e)),
403404
backtrace: backtrace,
404405
})
405406
};
406407
#[cfg(not(feature = "backtrace"))]
407-
let error = E::new(callback().into(), State {
408+
let error = CE::new(callback().into(), State {
408409
next_error: Some(Box::new(e)),
409410
});
410411
error

tests/tests.rs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -236,11 +236,20 @@ fn has_backtrace_depending_on_env() {
236236

237237
#[test]
238238
fn chain_err() {
239+
use std::fmt;
239240
use error_chain::ResultExt;
240241

241-
error_chain! {}
242+
error_chain! {
243+
foreign_links {
244+
fmt::Error, Fmt;
245+
}
246+
errors {
247+
Test
248+
}
249+
}
242250

243-
let _: Result<()> = Err("".into()).chain_err(|| "");
251+
let _: Result<()> = Err(fmt::Error).chain_err(|| "");
252+
let _: Result<()> = Err(ErrorKind::Test).chain_err(|| "");
244253
}
245254

246255
#[test]

0 commit comments

Comments
 (0)