use derive_enum_error::Error; use std::error::Error; #[derive(Debug, Error)] #[error(display = "An error has occurred.")] struct UnitError; #[test] fn unit_struct() { let s = format!("{}", UnitError); assert_eq!(&s[..], "An error has occurred."); } #[derive(Debug, Error)] #[error(display = "Error code: {}", code)] struct RecordError { code: u32, } #[test] fn record_struct() { let s = format!("{}", RecordError { code: 0 }); assert_eq!(&s[..], "Error code: 0"); } #[derive(Debug, Error)] #[error(display = "Error code: {}", _0)] struct TupleError(i32); #[test] fn tuple_struct() { let s = format!("{}", TupleError(2)); assert_eq!(&s[..], "Error code: 2"); } #[derive(Debug, Error)] enum EnumError { #[error(display = "Error code: {}", code)] StructVariant { code: i32 }, #[error(display = "Error: {}", _0)] TupleVariant(&'static str), #[error(display = "An error has occurred.")] UnitVariant, } #[test] fn enum_error() { let s = format!("{}", EnumError::StructVariant { code: 2 }); assert_eq!(&s[..], "Error code: 2"); let s = format!("{}", EnumError::TupleVariant("foobar")); assert_eq!(&s[..], "Error: foobar"); let s = format!("{}", EnumError::UnitVariant); assert_eq!(&s[..], "An error has occurred."); } #[derive(Debug, Error)] enum ErrorWithSource { #[error(display = "tuple error")] A(#[error(source)] TupleError), } #[test] fn error_with_source() { let e = ErrorWithSource::A(TupleError(1)); assert!(e.source().is_some()); }