Skip to content

Commit

Permalink
Implement std::error::Error for throw::Error (#8)
Browse files Browse the repository at this point in the history
* Implement std::error::Error for throw::Error

* std::error::Error impl now requires inner error also implements std::error::Error. Added tests for this impl.
  • Loading branch information
asib authored and daboross committed Oct 10, 2018
1 parent 884d472 commit b4d3c24
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,19 @@ where
}
}

impl<E> std::error::Error for Error<E>
where
E: std::error::Error
{
fn description(&self) -> &str {
self.error().description()
}

fn cause(&self) -> Option<&std::error::Error> {
Some(self.error())
}
}

#[macro_export]
macro_rules! up {
($e:expr) => (
Expand Down
55 changes: 55 additions & 0 deletions tests/exceptions_work.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,34 @@ fn throws_into_multiple_key_value_pairs() -> Result<(), String> {
Ok(())
}

#[derive(Debug)]
struct CustomError(String);

impl std::fmt::Display for CustomError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "CustomError: {}", self.0)
}
}

impl std::error::Error for CustomError {
fn description(&self) -> &str {
self.0.as_str()
}
}

fn throws_error_with_description() -> Result<(), CustomError> {
throw!(Err(CustomError("err".to_owned())));
Ok(())
}

fn throws_error_with_description_and_key_value_pairs() -> Result<(), CustomError> {
throw!(
Err(CustomError("err".to_owned())),
"key" => "value"
);
Ok(())
}

#[test]
fn test_static_message() {
let error = throw_static_message().unwrap_err();
Expand Down Expand Up @@ -219,3 +247,30 @@ fn test_throws_into_multiple_key_value_pairs() {
error
)
}

#[test]
fn test_error_description() {
use std::error::Error;

let error = throws_error_with_description().unwrap_err();
assert_eq!(error.description(), "err");
}

#[test]
fn test_error_description_with_key_value_pairs() {
use std::error::Error;

let error = throws_error_with_description_and_key_value_pairs().unwrap_err();
assert_eq!(error.description(), "err");
}

#[test]
fn test_error_with_cause() {
use std::error::Error;

let error = throws_error_with_description().unwrap_err();
assert_eq!(
format!("{}", error.cause().unwrap()),
"CustomError: err"
);
}

0 comments on commit b4d3c24

Please sign in to comment.