我正在尝试使用 Iron 框架在 Rust 中构建一个简单的后端。这个处理程序只是应该返回某个文件的内容,我可以让它正常工作,unwrap()
但我想尝试做正确的错误处理。这就是我想象的样子:
fn get_content(res: &mut Request) -> IronResult<Response> {
let mut id = String::new();
res.body.read_to_string(&mut id).unwrap();
let file_path_string = &("../content/".to_string() + &id + ".rdt");
// TODO: Error handling
match File::open(file_path_string) {
Ok(f) => {
let mut s = String::new();
f.read_to_string(&mut s);
Ok(Response::with(((status::Ok), s)))
}
Err(err) => Err(Response::with(((status::InternalServerError), "File not found")))
};
}
这会引发错误not all control paths return a value [E0269]
,这很好。但是如果我在匹配部分之后添加一个响应:
match File::open(file_path_string) {
Ok(f) => {
let mut s = String::new();
f.read_to_string(&mut s);
Ok(Response::with(((status::Ok), s)))
}
Err(err) => Err(Response::with(((status::InternalServerError), "File not found")))
};
Err(Response::with(((status::InternalServerError), "File not found")))
相反,我收到错误消息:
expected `iron::error::IronError`,
found `iron::response::Response`
(expected struct `iron::error::IronError`,
found struct `iron::response::Response`) [E0308]
src/main.rs:95
Err(Response::with(((status::InternalServerError), "File not found")))
我认为问题在于 Rust Err 和 Iron Err 之间的冲突?不过我不确定。而且我过去没有做过太多的 Web 开发(或 Rust),所以对代码的任何反馈也很感激!
更新:我认为这更像是“生锈方式”吗?但我不确定
fn get_content(res: &mut Request) -> IronResult<Response> {
let mut id = String::new();
res.body.read_to_string(&mut id).unwrap();
let file_path_string = &("../content/".to_string() + &id + ".rdt");
// TODO: Error handling
let f;
match File::open(file_path_string) {
Ok(file) => f = file,
Err(err) => Err(HttpError::Io(err))
};
let mut s = String::new();
f.read_to_string(&mut s);
Ok(Response::with(((status::Ok), s)))
}
在错误处理中包含代码似乎很奇怪,因为read_to_string
还需要注意,这会造成错误处理的嵌套混乱?然而,这些匹配的手臂显然是不兼容的类型,所以它不会工作......有什么建议吗?