A Macros 1.1 implementation of https://crates.io/crates/error-chain
The error-chain example
error_chain {
types { Error, ErrorKind, ChainErr, Result; }
links {
rustup_dist::Error, rustup_dist::ErrorKind, Dist;
rustup_utils::Error, rustup_utils::ErrorKind, Utils, #[cfg(unix)];
}
foreign_links {
temp::Error, Temp;
}
errors {
InvalidToolchainName(t: String) {
description("invalid toolchain name")
display("invalid toolchain name: '{}'", t)
}
}
}
becomes
#[derive(Debug, error_chain)]
// This attribute is optional if using the default names "Error", "Result" and "ChainErr"
#[error_chain(error = "Error", result = "Result", chain_err = "ChainErr")]
pub enum ErrorKind {
Msg(String), // A special variant that must always be present.
Dist(rustup_dist::Error, rustup_dist::ErrorKind),
#[cfg(unix)]
Utils(rustup_utils::Error, rustup_utils::ErrorKind),
#[error_chain(foreign)]
Temp(temp::Error),
#[error_chain(custom, description = "invalid_toolchain_name_description", display = "invalid_toolchain_name_display")]
InvalidToolchainName(String),
}
// A description function receives refs to all the variant constituents, and should return a &str
fn invalid_toolchain_name_description(_: &str) -> &str {
"invalid toolchain name"
}
// A display function receives a formatter and refs to all the variant constituents, and should return a ::std::fmt::Result
fn invalid_toolchain_name_display(f: &mut ::std::fmt::Formatter, t: &str) -> ::std::fmt::Result {
write!(f, "invalid toolchain name: '{}'", t)
}
Notes:
- This library requires the nightly compiler to be able to use the
proc_macro
andconservative_impl_trait
rust features. - The macro output can be used with
#[deny(missing_docs)]
since it allows doc comments on the ErrorKind variants. - The macro output uses
::backtrace::Backtrace
unlike error-chain which uses$crate::Backtrace
. Thus you need to link tobacktrace
in your own crate. - The backtrace type can be overridden from
::backtrace::Backtrace
by settingbacktrace = "SomeOtherPath"
. It can be disabled completely by setting it to an empty string. - The enum must always have a special
Msg(String)
member. Unlike error_chain which adds this member implicitly, this macro requires it explicitly.