Macro error

Source
error!() { /* proc-macro */ }
Expand description

This macro allows quickly defining errors in the format that this crate produces.

It has 5 major forms:

  • Unit struct:
error! {
    MyUnitError
    "it's a unit error"
}
  • Record struct:
error! {
    MyStructError
    "it's a struct! Field 2 is {field2:?}"
    field: Type,
    field2: Type2,
}
  • Enum:
error! {
    MyEnumError
    "it's a whole enum"
    SourceError1,
    MyUnitError,
    MyStructError,
}
  • Transparent enum:
error! {
    QuietAsAMouse
    MyEnumError,
    REALLY_LOUD_ERROR,
}
  • Array:
error! {
    ManyProblems
    "encountered many problems"
    [SomeError]
}

Each form implements Debug, Error, and From as appropriate. The enum forms implement std::error::Error::source() for each of their variants, and each variant must be the name of an existing error type. The struct form exposes the fields for use in the error message. The transparent enum form does not append a message, and simply passes the source along directly. All forms are #[non_exhaustive] and all fields are public. They can be made public by adding pub to the name like pub MyError.

Additional attributes can be added before the name to add them to the error type, like so:

error! {
    #[derive(PartialEq, Eq)]
    AttrsError
    "has attributes!"
    /// a number for something
    num: i32
}

Attributes can be added to fields and variants of struct/enum/array errors, and they can be made generic:

error! {
    /// In case of emergency
    BreakGlass<BreakingTool: std::fmt::Debug>
    "preferably with a blunt object"
    like_this_one: BreakingTool,
}

If cfg attributes are used, they’re copied to relevant places to ensure it compiles properly:

error! {
    #[cfg(feature = "drop_the_whole_error")]
    EnumErr
    "foo"
    #[cfg(feature = "foo")]
    Case1,
    #[cfg(feature = "bar")]
    Case2,
}

error! {
    StructErr
    "bar"
    #[cfg(feature = "foo")]
    field1: Foo,
    #[cfg(feature = "bar")]
    field2: Bar,
}

Make sure not to use cfg’d fields in the error message string if those fields can ever be not present.