rust - 使用rust 中未发现的错误

标签 rust

我有以下代码来打开文件并处理错误:

match File::open(&Path::new(file_name_abs.clone())) {
   Some(html_file) => {
       let mut html_file_mut = html_file;
       let msg_bytes: ~[u8] = html_file_mut.read_to_end();
       response.push_str(str::from_utf8(msg_bytes));
   },
   None => {
       println("not found!");
       valid = false;
   }   
}

当我传入一个无效文件时,仍然有以下错误信息:

task '<unnamed>' failed at 'Unhandled condition: io_error: io::IoError{kind: FileNotFound, desc: "no such file or directory", detail: None}', /private/tmp/rust-R5p2/rust-0.9/src/libstd/condition.rs:139

这里有什么问题?谢谢!

最佳答案

表示file_name_abs描述的文件在您指定的位置找不到。检查文件的路径。

我在我的系统上运行了这段代码(稍作修改)。如果找到文件,它会工作;如果没有,则给出“找不到文件”错误,如下所示:

task '<main>' failed at 'Unhandled condition: io_error: io::IoError{kind: FileNotFound, desc: "no such file or directory", detail: None}', /home/midpeter444/tmp/rust-0.9/src/libstd/condition.rs:139

此外,您可能不需要调用 clonefile_name_abs ,但这是次要问题,而不是您看到的运行时错误的原因。

[更新]:要在运行时处理错误,您有几个我知道的选项:

选项 1:在尝试打开文件之前检查文件是否存在:

let fopt: Option<File>;
if path.exists() && path.is_file() {
    fopt = File::open(&path);
} else {
    fopt = None;
}
// then do the match here


选项 2:使用 io::result功能:http://static.rust-lang.org/doc/0.9/std/io/fn.result.html .此函数将捕获任何 IO 错误并允许您检查 Result<T,Error>它返回以查看它是否成功或抛出错误。这是一个例子:

let path = Path::new(fname);

let result = io::result(|| -> Option<File> {
    return File::open(&path);
});

match result {
    Ok(fopt)      => println!("a: {:?}", fopt.unwrap()),
    Err(ioerror)  => println!("b: {:?}", ioerror)
}

或者,更通俗地说,(正如@dbaupp 所指出的那样):

let path = Path::new(fname);

let result = io::result(|| File::open(&path));

match result {
    Ok(fopt)      => println!("a: {:?}", fopt.unwrap()),
    Err(ioerror)  => println!("b: {:?}", ioerror)
}

关于rust - 使用rust 中未发现的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21372100/

相关文章:

error-handling - 我是否被迫创建自己的错误类型?

enums - 有没有办法创建枚举值的别名?

rust - 在遍历元素时移除元素

rust - 如何通过结构内容返回对迭代器的适当生命周期引用?

rust - 打印 Rust 中的所有结构字段

Rust 设计存储结构和只读结构用户的方法

rust - 特征对象的静态数组

rust - 断言特征对象的相等性?

rust - 如何为将作为闭包参数的关联类型指定生存期?

rust - 如果文件更短,如何读取文件的前 N ​​个字节或更短?