Derive Macro ErrorStack

Source
#[derive(ErrorStack)]
{
    // Attributes available to this derive:
    #[error_message]
}
Expand description

A derive-macro to easily create enums and structs compatible with error_stack. You can use a struct or an enum with it

§Panic

§Usage

use error_stack_derive::ErrorStack;

#[derive(ErrorStack, Debug)]
// error_message tokens can be any token stream as long as it evaluates
// to a &str
#[error_message("An error occured in Foo")]
struct FooError;

#[derive(ErrorStack, Debug)]
// The tokens are passed to the [`std::fmt::Formatter::write_str`]
// method of the [`std::fmt::Formatter`] in the automatically
// implemented Display impl. Passing an error message is mandatory
// for structs while its not for enums
// So you can do this too!
#[error_message(&format!("An internal error occured: {}", self.0))]
struct InternalError<A>(pub A)
where
    A: std::fmt::Display + std::fmt::Debug + Send + Sync + 'static;


// And ofcourse enums are supported too
#[derive(ErrorStack, Debug)]
// This is the default error message, this is used when a variant
// doesn't have a dedicated error message
// When a default error message is not specified and an enum doesn't
// have a dedicated message,
// `&format!("[{name}] An error occured; {:?}", name = #struct_name, self)` is passed to
// [`std::fmt::Formatter::write_str`]
#[error_message("Default error message")]
enum EncoderError {
    // For struct variants the name of the fields are left unchanged
    // but for tuple variants they are named `unnamed{pos}`
    #[error_message(&format!("Couldn't serialize data: {:?}", unnamed0))]
    SerializeError(String),
    DeserializeError,
}