Contextual error conversion with ? operator

Say I have some program that during initialization reads in two different files, Config and Data. The kind of error here could be PermissionDenied, NotFound, etc. Is there some idiomatic way of implementing From such that the ? operator could, for example, return OpenConfigFilePermissionDenied for an error operning the config file or OpenDataFileNotFound for the data file depending on the context of the error, ie where the error occurred.

The implementation of std::io::Error is interesting in this regard. It has Simple and Custom variants, but it still can't use any contextual information when converting to another error.

Is there some common pattern for this situation?

you could use .map_err on the result to convert the error type before the ? operator.

I love .map_err. One of my favorites, but I’d like to keep as much error handling in a separate module as possible.

Does this do what you want?

anyhow::Context

Hm, sorry i seem to have misunderstood your original question initially. Maybe backtrace could be abused to select the error based on the calling function, but i don't think that's cleaner than doing .map_err at the call site.

That's an interesting approach.

I always forget I can implement my own traits.

Thanks