Rust actix-web:特征 `Handler<_, _>` 未实现

ilm*_*moi 9 rust actix-web

我已从使用actix-web3.xx 转向 4.xx,之前运行良好的代码现在抛出此错误:

the trait bound `fn(actix_web::web::Query<TweetParams>, actix_web::web::Data<Pool<Postgres>>) -> impl std::future::Future {tweets4}: Handler<_, _>` is not satisfied
  --> src/routes/all_routes.rs:74:14
   |
74 | pub async fn tweets4(
   |              ^^^^^^^ the trait `Handler<_, _>` is not implemented for `fn(actix_web::web::Query<TweetParams>, actix_web::web::Data<Pool<Postgres>>) -> impl std::future::Future {tweets4}`
Run Code Online (Sandbox Code Playgroud)

经过一番谷歌搜索后,似乎生态系统中确实存在一个Handler特征actix(但是,我认为不是 actix-web)。

我不知道我需要在哪里实现该特征。错误消息似乎表明函数本身缺少它,但我的理解是你只能在structs和上实现特征enums,而不是函数?

这是处理程序代码:

#[get("/tweets4")]
pub async fn tweets4(
    form: web::Query<TweetParams>,
    pool: web::Data<PgPool>,
) -> Result<HttpResponse, HttpResponse> {
    let fake_json_data = r#"
    { "name": "hi" }
    "#;

    let v: Value = serde_json::from_str(fake_json_data)
        .map_err(|_| HttpResponse::InternalServerError().finish())?;

    sqlx::query!(
        r#"
        INSERT INTO users
        (id, created_at, twitter_user_id, twitter_name, twitter_handle, profile_image, profile_url, entire_user)
        VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
        "#,
        Uuid::new_v4(),
        Utc::now(),
        "3",
        "4",
        "5",
        "6",
        "7",
        v,
    )
        .execute(pool.as_ref())
        .await
        .map_err(|e| {
            println!("error is {}", e);
            HttpResponse::InternalServerError().finish()
        })?;

    Ok(HttpResponse::Ok().finish())
}

Run Code Online (Sandbox Code Playgroud)

我错了什么?

如果有帮助,整个项目都在 github

use*_*716 6

我有一个非常相似的问题。问题的根本原因是我忘记使用一个async函数。简而言之,在查看https://actix.rs/docs/response/#json-response上的文档时,请确保使用async fn index(name: web::Path<String>) -> Result<impl Responder>而不是fn index(name: web::Path<String>) -> Result<impl Responder>


ilm*_*moi 5

经过充分的尝试和错误后我发现:

  1. 错误实际上是说返回值缺少必要的实现,而不是函数本身(如果你是像我这样的初学者,从错误消息中看不出来......)
  2. 更具体地说,actix 似乎不喜欢内置HttpResponse错误类型,我不得不用我自己的错误类型替换:
#[derive(Debug)]
pub struct MyError(String); // <-- needs debug and display

impl std::fmt::Display for MyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "A validation error occured on the input.")
    }
}

impl ResponseError for MyError {} // <-- key

#[get("/tweets4")]
pub async fn tweets4(
    form: web::Query<TweetParams>,
    pool: web::Data<PgPool>,
) -> Result<HttpResponse, MyError> {
    let fake_json_data = r#"
    { "name": "hi" }
    "#;

    let v: Value = serde_json::from_str(fake_json_data).map_err(|e| {
        println!("error is {}", e);
        MyError(String::from("oh no")) // <-- here
    })?;

    sqlx::query!(
        //query
    )
        .execute(pool.as_ref())
        .await
        .map_err(|e| {
            println!("error is {}", e);
            MyError(String::from("oh no")) // <-- and here
        })?;

    Ok(HttpResponse::Ok().finish())
}
Run Code Online (Sandbox Code Playgroud)

希望将来能帮助别人!