gpt4 book ai didi

rust - 火箭的“响应者”特征未针对“结果”实现

转载 作者:行者123 更新时间:2023-12-03 11:42:00 26 4
gpt4 key购买 nike

我最近开始学习Rust,目前正在尝试创建一个小型API。我为API响应创建了自己的结构,为错误创建了枚举:

// API Response Structure
pub struct ApiResponse {
pub body: JsonValue,
pub status: Status,
}

// Enum for my "custom errors"
#[derive(Debug, Snafu, Clone, Serialize)]
pub enum Errors {
#[snafu(display("Unable to retrieve the specified entry."))]
NotFound,

#[snafu(display("Internal Server Error, unable to process the data."))]
ISE,
}

然后,我为我的API Response结构实现了 Responder<'_>特性:

impl<'r> Responder<'r> for ApiResponse {
fn respond_to(self, req: &Request) -> Result<Response<'r>, Status> {
Response::build_from(self.body.respond_to(req).unwrap())
.status(self.status)
.header(ContentType::JSON)
.ok()
}
}

但是,当我尝试使用所提到的内容时,似乎无法让我的函数返回 Result<JsonValue, Errors>。我对这个问题不太确定,我也不太熟悉Rust,所以任何文档/指针都将不胜感激。

这是返回响应类型的函数。

#[put("/users/<user_id>", format = "json", data = "<new_user>")]
pub fn update_user(
conn: DbConnection,
user_id: i32,
new_user: Json<NewUser>,
) -> Result<JsonValue, ApiResponse> {

match users::table.find(user_id).load::<User>(&*conn) {
Ok(result) => {
if result.len() < 1 {
let response = ApiResponse {
body: json!({
"message": Errors::NotFound
}),
status: Status::NotFound
};

return Err(response)
}
},

Err(e) => {
let response = ApiResponse {
body: json!({
"message": Errors::ISE
}),
status: Status::InternalServerError
};

return Err(response);
},
}

match diesel::update(users::table.filter(id.eq(user_id)))
.set((
user_name.eq(new_user.user_name.to_string()),
age.eq(new_user.age),
gender.eq(new_user.gender.to_string()),
))
.get_result::<User>(&*conn)
{
Ok(result) => Ok(json!(result)),
Err(_) => {
let res = ApiResponse {
body: json!({
"message": Errors::ISE
}),
status: Status::InternalServerError
};

return Err(res);
},
}
}

旁注:请记住,我仍然是Rust的初学者,而且我的错误处理/代码通常不是最好的。

编辑:我忘了包括错误堆栈:
error[E0277]: the trait bound `std::result::Result<rocket_contrib::json::JsonValue, api_cont::ApiResponse>: rocket::response::Responder<'_>` is not satisfied
--> src/routes.rs:72:6
|
72 | ) -> Result<JsonValue, ApiResponse> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `rocket::response::Responder<'_>` is not implemented for `std::result::Result<rocket_contrib::json::JsonValue, api_cont::ApiResponse>`
|
::: /home/kenneth/.cargo/registry/src/github.com-1ecc6299db9ec823/rocket-0.4.4/src/handler.rs:202:20
|
202 | pub fn from<T: Responder<'r>>(req: &Request, responder: T) -> Outcome<'r> {
| ------------- required by this bound in `rocket::handler::<impl rocket::Outcome<rocket::Response<'r>, rocket::http::Status, rocket::Data>>::from`
|
= help: the following implementations were found:
<std::result::Result<R, E> as rocket::response::Responder<'r>>
<std::result::Result<R, E> as rocket::response::Responder<'r>>

最佳答案

我也遇到了这个错误。
API Docs中提到了以下内容:

A type implementing Responder should implement the Debug trait when possible. This is because the Responder implementation for Result requires its Err type to implement Debug. Therefore, a type implementing Debug can more easily be composed.



这意味着您必须实现Debug,因为您将 ApiResponse用作 Err类型。

#[derive(Debug)]
pub struct ApiResponse {
pub body: JsonValue,
pub status: Status,
}

关于rust - 火箭的“响应者”特征未针对“结果”实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60860046/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com