Actix-web return Result

So even though actix-web impl Responder for Result<T, E>

This code won't compile:

use actix_web::*;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new().service(
            web::resource("/index.html").route(web::get().to(|| Ok(HttpResponse::Ok().finish()))),
        )
    })
    .bind("0.0.0.0:3000")?
    .run()
    .await
}

Giving error:

error[E0277]: the trait bound `[closure@src/main.rs:8:62: 8:96]: Factory<_, _, _>` is not satisfied
 --> src/main.rs:8:59
  |
8 |             web::resource("/index.html").route(web::get().to(|| Ok(HttpResponse::Ok().finish()))),
  |                                                           ^^ the trait `Factory<_, _, _>` is not implemented for `[closure@src/main.rs:8:62: 8:96]`

No matter what I do, I can't get it to work, and I really want it, because i want to use the ? operator! :frowning:

Any help?

Due to a limitation of rustc, we can't show a better error message than this, unfortunately.

There are a couple of rules to follow to make this work:

  • The error type cannot be inferred with how you have this set up. I would recommend using standalone functions over closures to avoid this problem.
  • Handler errors need to implement ResponseError.
  • Handlers need to return futures.

Therefore, a working code snippet would look like:

web::resource("/index.html")
    .route(web::get().to(|| async {
        Ok::<_, actix_web::Error>(HttpResponse::Ok().finish())
    })),
1 Like

Thank you Rob for helping me solve this. moving to ? has been a great boost to my code's ergonomics!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.