在尝试开始使用火箭开发 api 时,我正在实现一个请求保护,它应该检查授权标头。当检查失败时,它应该导致失败,但那是我无法让它工作的地方。Outcome::Success
工作得很好并返回正确的对象,但是在触发时Outcome::Failure
我总是遇到无法编译的问题:
error[E0282]: type annotations needed
--> src/main.rs:43:21
|
43 | Outcome::Failure((Status::BadRequest, RequestError::ParseError));
| ^^^^^^^^^^^^^^^^ cannot infer type for type parameter S declared on the enum Outcome
重现
main.rs
#[macro_use] extern crate rocket;
use rocket::Request;
use rocket::request::{FromRequest, Outcome};
use rocket::http::Status;
use regex::Regex;
#[get("/")]
fn index() -> &'static str {
"Hello, world!"
}
#[get("/test")]
fn test(device: Device) -> &'static str {
"Hello test"
}
#[derive(Debug)]
enum RequestError {
InvalidCredentials,
ParseError,
}
struct Device {
id: i32
}
#[rocket::async_trait]
impl<'r> FromRequest<'r> for Device {
type Error = RequestError;
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
Outcome::Failure((Status::BadRequest, RequestError::ParseError));
// TEST
let d1 = Device {
id: 123
};
Outcome::Success(d1)
}
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index,test])
}
货运.toml
[package]
name = "api-sandbox"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rocket = "0.5.0-rc.1"
regex = "1"
预期行为
参数 S 不需要声明,因为我没有使用参数 Success(S),而是使用 Failure(E)。根据文档,我可以返回错误或带有状态和错误的元组,但会弹出错误消息。我只仔细检查了可用资源和博客,但无法正确触发状态失败的结果。
环境:
VERSION="20.04.3 LTS (Focal Fossa)"
5.10.60.1-微软标准-WSL2
火箭 0.5.0-rc.1
我对这个主题很陌生,所以如果我需要提供更多信息,请告诉我。感谢您在此主题上的帮助