Rust actix-web : the trait `Handler<_, _>` is not implemented

标签 rust actix-web rust-actix

我已经不再使用 actix-web 3.x.x 到 4.x.x。之前运行良好的代码现在抛出此错误:

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}`
经过一番谷歌搜索后,似乎 there is indeed a Handler traitactix生态系统(但是,我认为不是 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())
}

我怎么了?
如果有帮助,整个项目在 github here .

最佳答案

经过充分的反复试验,我发现:

  • 错误实际上是说返回值缺少必要的实现,而不是函数本身(如果您是像我这样的初学者,从错误消息中看不出来...)
  • 更具体地说,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())
    }
    
    希望对 future 的人有所帮助!

    关于Rust actix-web : the trait `Handler<_, _>` is not implemented,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67811502/

    相关文章:

    binding - let-rebinding 和标准赋值有什么区别?

    rust - 如何用重复的 u16 值填充 [u8] 数组?

    rust - 如何在actix_web FromRequest特征实现中返回映射的将来? [复制]

    rust - Actix Web actor的创建不止一次

    rust - 如何解析包含简单列表和键值列表(关联数组)的YAML

    string - 拆分字符串并跳过空子字符串

    postgresql - Rust Actix-Web sqlx 可选功能 `time` 需要列 #4 ("created_at"的 TIMESTAMPTZ 类型)

    rust - 如何设置 actix websocket actorless 的消息大小限制?

    mongodb - Rust Actix Web 是否支持 MongoDB?