Deriving `Error`

Unless there were desire to implement it on enums as well. The source is optional, so it's not like each variant would have to have the source attribute.

Something like this would be possible:

#[derive(Error)] // assume Debug and Display are implemented
enum MyError {
    Foo,
    Bar {
        #[source]
        internal_error: io::Error,
    },
    Baz(#[source] io::Error),
}

could generate the following

impl ::std::error::Error for MyError {
    fn source(&self) -> Option<&(dyn ::std::error::Error + 'static)> {
        match *self {
            MyError::Foo => None,
            MyError::Bar { internal_error, .. } => Some(internal_error),
            MyError::Baz(_0) => Some(_0),
        }
    }
}

As I've said before, I believe this to be feasible to generate procedurally.

1 Like

I'm tenatively against adding a #[derive(Error)] that simply expands to impl std::error::Error for MyType {} with no support for backtrace or source.

My understanding is that if you wanted to add any custom handling for source / backtrace you'd have to remove the derive and type it out manually anyway. This seems like we'd just be adding a derive to save typing 10ish characters. When a new user wants to go and implement an error that has a root cause or a backtrace they're going to waste time trying to figure out how to do that via the derive only to eventually learn that it's just a short hand for an empty Error trait impl that they never learned how to work with in the first place. This seems like an unnecessary source of confusion for almost no gain.

That said, I'm totally in favor of something like thiserror getting into std with the accompanying attributes and support for backtrace / source / transparent errors and possibly some sort of basic Display derive to go alongside it, though I think that display derive should be more similar to thiserror's display derive in implementation than displaydoc's. I would not want to force people to use their doc comments as their display impls.

6 Likes

FWIW the derive_more crate just added a derive for Error in the latest release. There's a bit too much magic for my liking (automatically using a field named source, for example), but the general idea is quite similar to those in this thread.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.