Skip to main content

Error

Derive Macro Error 

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

Derive Display and Error implementations from #[error(...)] declarations.

A format string defines ordinary display behavior.

#[derive(Error, Debug)]
#[error("failed to read {path}")]
struct ReadError {
    path: String,
}

source(field) selects the ordinary error source.

#[derive(Error, Debug)]
#[error("network request failed")]
#[error(source(io))]
struct NetworkError {
    io: std::io::Error,
}

transparent(field) requires exactly one non-optional field. Display forwards to that field and source chaining forwards through the field’s own Error::source implementation.

#[derive(Error, Debug)]
#[error(transparent(0))]
struct Wrapper(std::io::Error);

from requires exactly one field. It generates From<T> and selects that field as the ordinary source.

#[derive(Error, Debug)]
#[error("parse failed")]
#[error(from)]
struct ParseError(std::num::ParseIntError);

display(path) selects a custom formatter function.

fn render(error: &Rendered, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    let Rendered { code } = error;
    write!(f, "rendered {code}")
}

#[derive(Error, Debug)]
#[error(display(render))]
struct Rendered {
    code: u8,
}

Inline control is optional. Omitting it emits no explicit inline attribute. inline and inline(neutral) emit ordinary #[inline]. The always and never strategies emit the corresponding Rust attributes.

#[derive(Error, Debug)]
#[error(inline(never))]
#[error("rare error")]
struct RareError;

Generated paths use ::core by default. import(path) selects a different root.

#[derive(Error, Debug)]
#[error(import(::std))]
#[error("standard error")]
struct StdError;