1 #![deny(clippy::all, clippy::pedantic)]
2
3 use anyhow::anyhow;
4 use std::error::Error as _;
5 use std::io;
6 use thiserror::Error;
7
8 #[test]
test_transparent_struct()9 fn test_transparent_struct() {
10 #[derive(Error, Debug)]
11 #[error(transparent)]
12 struct Error(ErrorKind);
13
14 #[derive(Error, Debug)]
15 enum ErrorKind {
16 #[error("E0")]
17 E0,
18 #[error("E1")]
19 E1(#[from] io::Error),
20 }
21
22 let error = Error(ErrorKind::E0);
23 assert_eq!("E0", error.to_string());
24 assert!(error.source().is_none());
25
26 let io = io::Error::new(io::ErrorKind::Other, "oh no!");
27 let error = Error(ErrorKind::from(io));
28 assert_eq!("E1", error.to_string());
29 error.source().unwrap().downcast_ref::<io::Error>().unwrap();
30 }
31
32 #[test]
test_transparent_enum()33 fn test_transparent_enum() {
34 #[derive(Error, Debug)]
35 enum Error {
36 #[error("this failed")]
37 This,
38 #[error(transparent)]
39 Other(anyhow::Error),
40 }
41
42 let error = Error::This;
43 assert_eq!("this failed", error.to_string());
44
45 let error = Error::Other(anyhow!("inner").context("outer"));
46 assert_eq!("outer", error.to_string());
47 assert_eq!("inner", error.source().unwrap().to_string());
48 }
49
50 #[test]
test_anyhow()51 fn test_anyhow() {
52 #[derive(Error, Debug)]
53 #[error(transparent)]
54 struct Any(#[from] anyhow::Error);
55
56 let error = Any::from(anyhow!("inner").context("outer"));
57 assert_eq!("outer", error.to_string());
58 assert_eq!("inner", error.source().unwrap().to_string());
59 }
60