如何在 Rust 中对 File-Reader 进行正确的错误处理

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

我想将 Json 文件加载到 Vec。

当我用 unwrap() 做所有事情时,它工作正常。现在我想捕捉一些错误,如“找不到文件”并处理它们,但我可能不知道该怎么做。

也许你能帮我?提前致谢。

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

您需要检查 ErrorKind 值是多少。如果是 NotFound,那么您就知道该文件不存在。

在您的代码中:

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

,其中有 Err(e) match arm, the type of e is std::io::Error. That struct has a method kind(),这是您需要检查的内容。像这样:

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