How to get filepath from std::io::Error

I want to print an error for user, I use:

match err {
    Error::Io(err) => {
        let err: std::io::Error = err;
        eprintln!("error: {}", err);
        // ..
    // ..

Sometimes an user has to specify a file to read, but if the file not found it prints error: No such file or directory (os error 2)

How can I print more informative message in particular what the path was specified?

You can't, from there. The path is not in that error, so you'll have to handle the error somewhere where you know the path, and create an error that contains both (enough information from) the io::Error and the Path.

A nice and easy way to do that is with the context method of the anyhow crate, like in the second example on the anyhow documentation front page.


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.