Hi,
I’m trying to use ? with client with this code:
async fn index(Form(login): Form<Login>)-> Response<String>{
let client = Client::with_uri_str("mongodb+srv://user:pass@cluster0.um0c2p7.mongodb.net/?retryWrites=true&w=majority").await?;
let db = client.database("db").collection::<Login>("coll");
//...
Ok(Response::builder().status(axum::http::StatusCode::OK)
.header("Content-Type", "text/html; charset=utf-8")
.body(tera.render("index", &context).unwrap()).unwrap())
}
But this error appears:
#9 319.5 error[E0277]: the `?` operator can only be used in an async function that returns `Result` or `Option` (or another type that implements `FromResidual`)
#9 319.5 --> src/main.rs:51:126
#9 319.5 50 | async fn index(Form(login): Form<Login>)-> Response<String>{
#9 319.5 | ______________________________________________________________-
#9 319.5 51 | | let client = Client::with_uri_str("***cluster0.um0c2p7.mongodb.net/?retryWrites=true&w=majority").await?;
#9 319.5 | | ^ cannot use the `?` operator in an async function that returns `Response<std::string::String>`
#9 319.5 52 | | let db = client.database("db").collection::<Login>("coll");
#9 319.5 53 | | let deb: Login = db.find_one(doc!{"user":"test"},None).await?;
#9 319.5 65 | | .body(tera.render("index", &context).unwrap()).unwrap()
#9 319.5 66 | | }
#9 319.5 | |_- this function should return `Result` or `Option` to accept `?`
#9 319.5 = help: the trait `FromResidual<Result<Infallible, mongodb::error::Error>>` is not implemented for `Response<std::string::String>`
I tried to use result in many ways and it didn’t work either, is there a solution for this problem?
let client = Client::with_uri_str("mongodb+srv://user:pass@cluster0.um0c2p7.mongodb.net/?retryWrites=true&w=majority").await.unwrap();
Note that using unwrap means your code will panic if there’s an error, which will likely cause the program to terminate. This is fine for test code and proof of concept, but for anything beyond that I recommend using a Result. The Rust book has a good chapter on how to handle errors, if you haven’t read it yet I highly recommend it
I’m not at all familiar with Axum, but as far as I can tell from its documentation the return type needs to use StatusCode as the error type, not Box<dyn Error>; you’ll need to convert errors produced by methods you call within your handler to that.
I’d also recommend against creating a new Client for each request; Client construction is heavyweight, and while that will work, it’ll be slow. It looks like Axum provides good support for state shared across handlers, so that sounds like the way to go.