我正在创建rust Web应用程序。我对此并不陌生,我正在尝试提出API请求,并将请求的结果作为对Web视图的响应传递给请求。有main.rs,route.rs和common.rs文件。基本上main.rs文件调用相关的路由,然后route将调用该函数。
但是,route.rs文件中的函数存在错误。
error[E0277]: the trait bound `fn() -> impl std::future::Future {<search::routes::get_token as actix_web::service::HttpServiceFactory>::register::get_token}: actix_web::handler::Factory<_, _, _>` is not satisfied
--> src\search\routes.rs:20:10
|
20 | async fn get_token() -> Result<String, reqwest::Error> {
| ^^^^^^^^^ the trait `actix_web::handler::Factory<_, _, _>` is not implemented for `fn() -> impl std::future::Future {<search::routes::get_token as actix_web::service::HttpServiceFactory>::register::get_token}`
我该如何解决?
route.rs
use crate::search::User;
use actix_web::{get, post, put, delete, web, HttpResponse, Responder};
use serde_json::json;
extern crate reqwest;
extern crate serde;
mod bfm;
mod common;
#[get("/token")]
async fn get_token() -> Result<String, reqwest::Error> {
let set_token = common::authenticate();
// let set_token = common::get_rust_posts();
return set_token.await;
//HttpResponse::Ok().json(set_token)
}
common.rs
extern crate reqwest;
use reqwest::header::HeaderMap;
use reqwest::header::AUTHORIZATION;
use reqwest::header::CONTENT_TYPE;
pub async fn authenticate() -> Result<String, reqwest::Error> {
fn construct_headers() -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert(AUTHORIZATION, "Basic bghythjuikyt==".parse().unwrap());
headers.insert(CONTENT_TYPE, "application/x-www-form-urlencoded".parse().unwrap());
assert!(headers.contains_key(AUTHORIZATION));
assert!(!headers.contains_key(CONTENT_TYPE));
headers
}
let client = reqwest::Client::new();
let reszr = client.post("https://api.test.com/auth/token")
.headers(construct_headers())
.body("grant_type=client_credentials")
.send()
.await?
.text()
.await;
return reszr;
}
答案 0 :(得分:1)
首先,请阅读:https://actix.rs/docs/errors/
-
您是否为ResponseError
实现了reqwest::Error
?
您必须实现ResponseError
特性,因为在Result
为Err
的情况下,框架必须做出响应。
这是一个例子
impl ResponseError for Error {
fn error_response(&self) -> HttpResponse {
match self.kind_ref() {
ErrorKind::HttpResponse { msg, code, real } => {
println!("{}", real);
HttpResponse::build(code.to_owned()).json(json!({
"status": false,
"msg": msg
}))
}
_ => {
println!("{}", self);
HttpResponse::build(StatusCode::INTERNAL_SERVER_ERROR).finish()
}
}
}
}
Error
是我的自定义错误,其中包含msg
,code
,real
,但是在您的情况下逻辑应该相似。
-
更新:@Masklinn在评论error[E0117]: only traits defined in the current crate can be implemented for arbitrary types
上面的代码仅适用于您拥有的自定义Error
。
您可以做的是:
将reqwest::Error
映射到已经实现Error
的{{1}}。您可以在此处查看实施列表:https://docs.rs/actix-web/3.0.0-alpha.1/actix_web/trait.ResponseError.html#implementors
创建包装ResponseError
(以及代码中的其他错误)的自定义Error
并在其上实现reqwest::Error
(基本上与第一个相同/相似)