gpt4 book ai didi

rust - Actix actor 的错误处理和条件链接

转载 作者:行者123 更新时间:2023-11-29 08:31:04 29 4
gpt4 key购买 nike

这是我第一次尝试使用 actix-web 编写带有 Rust 的小型 Web 服务。

下面的代码是一个请求处理程序,旨在做三件事,在数据库中插入一个条目,如果数据库调用成功则发送一封电子邮件,然后返回一个 json 负载作为响应。

data.dal(数据库调用)和 data.email_service 是对 Actors 的引用。

问题:我无法捕获 data.dal 返回的错误。任何重新配置​​以下代码的尝试似乎都会给我一个错误,指出编译器无法找到从 Actix Mailbox 到 [Type] 的转换。

是否有替代/更好的方法来重写它?基本上当发出请求时,我希望能够调用 Actor A。如果 A 的结果是好的,那么调用 Actor B。如果两者的结果都可以,则返回一个 JSON 负载。如果 A 或 B 返回错误(可以有不同的错误类型),则返回自定义错误消息。

pub fn register_email(
invitation: Json<EmailInvitationInput>,
data: web::Data<AppState>,
) -> impl Future<Item=HttpResponse, Error=Error> {
let m = dal::queries::CreateEmailInvitation { email: invitation.email.clone() };
data.dal.send(m)
.from_err()
.and_then(move |res| {
let invite = res.unwrap();
let email_input = email::SendLoginLink {
from: "from_email".to_string(),
to: "to_email".to_string(),
};
data.email_service.send(email_input)
.from_err()
.and_then(move |res| match res {
Ok(_) => {
Ok(HttpResponse::Ok().json(EmailInvitationOutput { expires_at: invite.expires_at }))
}
Err(err) => {
debug!("{:#?}", err);
Ok(ServiceError::InternalServerError.error_response())
}
})
})
}

最佳答案

我通常做的是有一个 Error 类型,它聚集了所有不同的错误,可以通过声明适当的 From 实现和什么来隐式地实现对这种类型的强制转换你正在做 from_err() 但我在这里很明确:

我还没有测试过这段代码片段,但这是我在使用 Actix 的项目中完成的:

data.dal.send(m)
.map_err(Error::Mailbox)
.and_then(|res| res.map_err(Error::Service))
.and_then(move |invite| {
let email_input = email::SendLoginLink {
from: "from_email".to_string(),
to: "to_email".to_string(),
};
data.email_service.send(email_input)
.map_err(Error::Mailbox)
.and_then(|res| res.map_err(Error::Service))
.and_then(move |res| HttpResponse::Ok().json(EmailInvitationOutput { expires_at: invite.expires_at }))
})
.or_else(|err| {
debug!("{:#?}", err);
ServiceError::InternalServerError.error_response()
})

(我假设 ServiceErrorHttpResponse 一样实现了 IntoFuture)

关于rust - Actix actor 的错误处理和条件链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57779414/

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