简体   繁体   中英

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");
            }
        }
    }; 
}

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 isstd::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!");
        }
        ...
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM