Skip to content

Commit b4d3c24

Browse files
asibdaboross
authored andcommitted
Implement std::error::Error for throw::Error (#8)
* 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.
1 parent 884d472 commit b4d3c24

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

src/lib.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -588,6 +588,19 @@ where
588588
}
589589
}
590590

591+
impl<E> std::error::Error for Error<E>
592+
where
593+
E: std::error::Error
594+
{
595+
fn description(&self) -> &str {
596+
self.error().description()
597+
}
598+
599+
fn cause(&self) -> Option<&std::error::Error> {
600+
Some(self.error())
601+
}
602+
}
603+
591604
#[macro_export]
592605
macro_rules! up {
593606
($e:expr) => (

tests/exceptions_work.rs

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,34 @@ fn throws_into_multiple_key_value_pairs() -> Result<(), String> {
9393
Ok(())
9494
}
9595

96+
#[derive(Debug)]
97+
struct CustomError(String);
98+
99+
impl std::fmt::Display for CustomError {
100+
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
101+
write!(f, "CustomError: {}", self.0)
102+
}
103+
}
104+
105+
impl std::error::Error for CustomError {
106+
fn description(&self) -> &str {
107+
self.0.as_str()
108+
}
109+
}
110+
111+
fn throws_error_with_description() -> Result<(), CustomError> {
112+
throw!(Err(CustomError("err".to_owned())));
113+
Ok(())
114+
}
115+
116+
fn throws_error_with_description_and_key_value_pairs() -> Result<(), CustomError> {
117+
throw!(
118+
Err(CustomError("err".to_owned())),
119+
"key" => "value"
120+
);
121+
Ok(())
122+
}
123+
96124
#[test]
97125
fn test_static_message() {
98126
let error = throw_static_message().unwrap_err();
@@ -219,3 +247,30 @@ fn test_throws_into_multiple_key_value_pairs() {
219247
error
220248
)
221249
}
250+
251+
#[test]
252+
fn test_error_description() {
253+
use std::error::Error;
254+
255+
let error = throws_error_with_description().unwrap_err();
256+
assert_eq!(error.description(), "err");
257+
}
258+
259+
#[test]
260+
fn test_error_description_with_key_value_pairs() {
261+
use std::error::Error;
262+
263+
let error = throws_error_with_description_and_key_value_pairs().unwrap_err();
264+
assert_eq!(error.description(), "err");
265+
}
266+
267+
#[test]
268+
fn test_error_with_cause() {
269+
use std::error::Error;
270+
271+
let error = throws_error_with_description().unwrap_err();
272+
assert_eq!(
273+
format!("{}", error.cause().unwrap()),
274+
"CustomError: err"
275+
);
276+
}

0 commit comments

Comments
 (0)