shepmaster / snafu

Easily assign underlying errors into domain-specific errors while adding context
https://docs.rs/snafu/
Apache License 2.0
1.45k stars 61 forks source link

Suggestion: turn off struct generation for a variant (use case: implementing From for that variant instead) #244

Closed Ploppz closed 4 years ago

Ploppz commented 4 years ago

I've been using Snafu for many months and I get the idea that your error enum doesn't just impl From<OtherError> but converts from other errors by adding context. However, sometimes I want there to be one effortless and general way to convert from one error (in my case ApiError) to another (the main Error), without adding any context. Especially when the source error (ApiError) is just another snafu error enum that I made for my applicaiton. Say, for the sake of hierarchy. But also because one function I made, send_request(), returns Result<_, ApiError> Actually, I would like to optionally attach context to the error returned from send_request(), so that sometimes I can call send_request()? and other times send_request().context(err::PollWorker)?. What I have now:

pub enum Error {
    // ...
    FromApiError {
        source: ApiError,
    },
    #[snafu(display("Could not contact worker: {}", source))]
    PollWorker {
        source: ApiError,
    },
    #[snafu(display("Could not delete worker job: {}", source))]
    DeleteWorkerJob {
        source: ApiError,
    },
}

Then I will impl From<ApiError> for Error, which converts to Error::FromApiError I think. No major problems here, but I wish there was some way, through attributes, that I could disable struct generation for the variant FromApiError, making From the only way to construct it (apart from manual construction).

shepmaster commented 4 years ago

I’m pretty sure you are describing https://docs.rs/snafu/0.6.8/snafu/guide/attributes/index.html#controlling-context please let know if there’s something different and I’ll reopen.