gpt4 book ai didi

rust - Actix-web : send message to db handler, 有条件地向第二个处理程序发送消息

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

我正在尝试向一个数据库处理程序发送消息,并根据结果向第二个处理程序发送消息,或者从第一个处理程序返回错误。

到目前为止,我想出的办法都行不通; rustc 说 match arms have incompatible types

预期结构 'futures::future::and_then::AndThen',找到枚举 'std::result::Result'

state
.db
.send(...)
.from_err()
.and_then(|res| match res {
Ok(response) => {
// Do some additional logic here
state
.db
.send(...)
.from_err()
.and_then(|res| match res {
Ok(response) => Ok(HttpResponse::Ok().json(response)),
Err(err) => Ok(HttpResponse::InternalServerError().body(err.to_string()))
})
},
Err(err) => Ok(HttpResponse::InternalServerError().body(err.to_string()))
})
.responder()

问题如何在 actix-web 中完成这个?

最佳答案

你快到了。

使用 match 时, 所有武器必须产生相同的类型。在您的情况下,一个是与 and_then 结合的 future ,在另一只 ARM 上,你有一个 result .

此外,除非您的 send()函数返回类型 impl Future<Item = Result<R, E>, Error = E> , match完全是多余的。 and_thenItem 作为参数, 不是 Result<Item, Error> .

所以,整个事情可以简化为:

state
.db
.send(...)
.from_err()
.and_then(|res| state.db.send(...).from_err())
.then(|res| match res {
Ok(response) => Ok(HttpResponse::Ok().json(response)),
Err(err) => Ok(HttpResponse::InternalServerError().body(err.to_string()))
})
.responder()

不过,我们假设您的类型是正确的。您可以轻松转换 Result进入futurefuture::result像这样:

state
.db
.send(...)
.from_err()
.and_then(|res| future::result(res).from_err())
.and_then(|res|
// Do some additional logic here
state
.db
.send(...)
.from_err()
)
.and_then(|res| future::result(res).from_err())
.then(|res| match res {
Ok(response) => Ok(HttpResponse::Ok().json(response)),
Err(err) => Ok(HttpResponse::InternalServerError().body(err.to_string()))
})
.responder()

沙盒上有一个例子:https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=6801886b02081160e268f395bcc1ad6c

关于rust - Actix-web : send message to db handler, 有条件地向第二个处理程序发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54164682/

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