niklasb
niklasb

Reputation: 33

How to do I proper Error-Handling for a File-Reader in Rust

I would like to load a Json file to a Vec.

When I do everything with unwrap() it works fine. Now I want to Catch some Errors like "File not Found" and Handle them, but I'm not able to figure out how to do it probably.

Maybe you could help me? Thanks in advance.

fn read_from_file(filename: &str) -> Result<Vec<Card>, io::Error> {
    let f = File::open(filename);
    let mut f = match f {
        Ok(file) => file,
        Err(e) => return Err(e),
    };
    let mut s = String::new();
    f.read_to_string(&mut s)?;

    let data = serde_json::from_str(&s)?;
    Ok(data)
}

fn main() {
    let mut cards = read_from_file("Test.json");
    let mut cards = match cards {
        Ok(Vec) => Vec,
        Err(_) => {
            println!(
                "File was not found!\n 
            Do you want to create a new one? (y/N)"
            );
            let mut answer = String::new();
            io::stdin()
                .read_line(&mut answer)
                .expect("Failed to read line");
            answer.pop();
            if answer == "y" {
                let mut cards: Vec<Card> = Vec::new();
                return cards;
            } else {
                panic!("No file was found and you did not allow to create a new one");
            }
        }
    }; 
}

Upvotes: 3

Views: 3474

Answers (1)

at54321
at54321

Reputation: 11728

You need to check what the ErrorKind value is. If it is NotFound, then you know the file doesn't exist.

In your code:

let f = File::open(filename);
let mut f = match f {
    Ok(file) => file,
    Err(e) => return Err(e),
};

, where you have Err(e) match arm, the type of e is std::io::Error. That struct has a method kind() which is what you need to check. Like this:

let mut f = match f {
    Ok(file) => file,
    Err(e) => {
        if e.kind() == ErrorKind::NotFound {
            println!("Oh dear, the file doesn't exist!");
        }
        ...
    }
};

Upvotes: 4

Related Questions