Juan Leni
Juan Leni

Reputation: 7638

How to extend errors based on quick-error?

Let's say I have a crate Lib1 that declares something like:

#[macro_use]
extern crate quick_error;

quick_error! {
    #[derive(Debug)]
    pub enum MyError {
        Foo {
            description("FooError")
        }
    }
}

I have some another library Lib2 that depends on Lib1.

I would like to extend this MyError with some additional errors that are specific to Lib2. That way I can reuse all the base errors that were declared in Lib1.

Btw, I have complete control on both libraries and I can modify them as much as I need to. I definitely would like to keep using quick-error for this. Is it possible to extend this somehow?

Note: I already had a look at Can I extend an enum with additional values? That was definitely something I knew about before opening the question. This does not solve this specific problem. Ideally I would like to keep using quick_error. Plus using composition for error makes error handling downstream very complicated. Is there a nice pattern for extending errors in libraries?

Upvotes: 1

Views: 233

Answers (1)

E_net4
E_net4

Reputation: 30092

As described in Can I extend an enum with additional values?, composition of other enums is possible and common practice for creating an extended sum type designated to errors. The same idea can be applied to error types created with quick_error, by passing other errors as the cause of your own type. Considering a hypothetical crate lib2:

#[macro_use]
extern crate quick_error;
extern crate lib2;

quick_error! {
    #[derive(Debug)]
    pub enum MyError {
        Foo {
            description("FooError")
        },
        Lib2(err: lib2::Error) {
            description("Failed to do something done by lib2")
            from() // derive `From<lib2::Error>`, very useful
            cause(err)
        }
    }
}

The from() clause makes the compiler derive From<lib2::Error> for MyError. This is particularly useful, as it makes raising a Result<T, MyError> on a lib2 error as simple as employing the ? operator.

Upvotes: 2

Related Questions