How can I reliably match on an Error type?


I have a function that returns a Result<Vec, anyhow::Error>. I'm trying to match on "file not found", and this works on my machine:

        let recovered =
            "The system cannot find the file specified. (os error 2)"

This then fails on a different system be cause the error returned is "No such file or directory (os error 2)" (note it's slightly different). I don't fill my code with different wording for different systems.

If I debug print the recovered variable I get:

Os {
    code: 2,
    kind: NotFound,
    message: "The system cannot find the file specified.",

But I've tried all sorts of variations of calling downcast_ref trying to match against "NotFound" and I always get "None" back. I do feel matching on a "Kind" is a much more correct thing to do than matching on a string (and I'm surprised a lot of Google hits just recommend the latter) but I can't make the thing work.

Downcast to io::Error and check its .kind().


Thank you! That's exactly the intention I had, but that playground showed me several issues. Thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.