risingwave_common::error

Derive Macro ContextInto

#[derive(ContextInto)]
{
    // Attributes available to this derive:
    #[thiserror_ext]
    #[context_into]
}
Expand description

Generates extension traits for converting the external error type into the the provided one, with extra context.

This can be helpful when the external error type does not provide enough context for the application. thiserror does not allow specifying #[from] on the error field if there’re extra fields in the variant.

The extension trait is only generated when there’s a field named source or marked with #[source] but not #[from]. The rest of the fields (except the backtrace) are treated as the context. Both single and multiple context fields are supported.

§Example

#[derive(Debug, thiserror::Error, thiserror_ext::ContextInto)]
enum Error {
    #[error("cannot parse int from `{from}`")]
    ParseInt {
        source: std::num::ParseIntError,
        from: String,
    },

    #[error("cannot parse float from `{from}`")]
    #[context_into(skip)] // to skip generating the extension
    ParseFloat {
        source: std::num::ParseIntError,
        from: String,
    },
}

// Specify the `from` as "foo" and convert it into `Error::ParseInt`.
let _: Error = "foo".parse::<i32>().unwrap_err().into_parse_int("foo");

// Can also be called on `Result<T, ExternalError>`
let _: Result<i32, Error> = "foo".parse().into_parse_int("foo");

// Call `into_*_with` with a closure to lazily evaluate the context.
let _: Result<i32, Error> = "foo".parse().into_parse_int_with(|| format!("{}", 1 + 1));

§New type

If a new type is specified with #[thiserror_ext(newtype(..))], the extensions will convert the errors into the new type instead.

See the documentation of thiserror_ext::Box or thiserror_ext::Arc for more details.