1 unstable release
0.0.1 | Jul 4, 2019 |
---|
#27 in #derive-error
11KB
171 lines
errorderive
A failure-like derive macro for the std::error::Error
.
The source code is mostly copied from failure_derive & err-derive.
Compare with err-derive
- Support
edition = "2018"
- Rust version requires >= 1.30.0
- Use
source
keyword instead ofcause
- Use
call_site
for more debug information
lib.rs
:
errorderive
Deriving error sources
Add an #[error(source)]
attribute to the field:
use errorderive::Error;
use std::io;
/// `MyError::source` will return a reference to the `io_error` field
#[derive(Debug, Error)]
#[error(display = "An error occurred.")]
struct MyError {
#[error(source)]
io_error: io::Error,
}
#
Formatting fields
use errorderive::Error;
use std::path::PathBuf;
#[derive(Debug, Error)]
pub enum FormatError {
#[error(display = "invalid header (expected: {:?}, got: {:?})", expected, found)]
InvalidHeader {
expected: String,
found: String,
},
// Note that tuple fields need to be prefixed with `_`
#[error(display = "missing attribute: {:?}", _0)]
MissingAttribute(String),
}
#[derive(Debug, Error)]
pub enum LoadingError {
#[error(display = "could not decode file")]
FormatError(#[error(source)] FormatError),
#[error(display = "could not find file: {:?}", path)]
NotFound { path: PathBuf },
}
#
Printing the error
use std::error::Error;
fn print_error(e: &dyn Error) {
eprintln!("error: {}", e);
let mut source = e.source();
while let Some(e) = source {
eprintln!("sourced by: {}", e);
source = e.source();
}
}
Dependencies
~2MB
~48K SLoC