4

Trying to make server with actix-web & mongodb in rust. Getting error

the trait std::convert::From<mongodb::error::Error> is not implemented for std::io::Error

here is my code

use actix_web::{web, App, HttpRequest, HttpServer, Responder};
use mongodb::{options::ClientOptions, Client};

async fn greet(req: HttpRequest) -> impl Responder {
    let name = req.match_info().get("name").unwrap_or("World");
    format!("Hello {}!", &name)
}

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    // Parse a connection string into an options struct.
    let mut client_options = ClientOptions::parse("mongodb://localhost:27017")?;

    // Manually set an option.
    client_options.app_name = Some("My App".to_string());

    // Get a handle to the deployment.
    let client = Client::with_options(client_options)?;

    // List the names of the databases in that deployment.
    for db_name in client.list_database_names(None)? {
        println!("{}", db_name);
    }

    HttpServer::new(|| {
        App::new()
            .route("/", web::get().to(greet))
            .route("/{name}", web::get().to(greet))
    })
    .bind("127.0.0.1:8000")?
    .run()
    .await
}

Did I missed anything?

Niraj Gawande
  • 137
  • 1
  • 11
  • Please [edit] your question and paste the exact and entire error that you're getting — that will help us to understand what the problem is so we can help best. Sometimes trying to interpret an error message is tricky and it's actually a different part of the error message that's important. Please use the message from running the compiler directly, not the message produced by an IDE, which might be trying to interpret the error for you. – Shepmaster Apr 28 '20 at 12:24

1 Answers1

7

Reasoning

It means that one of the functions you are calling with a ? at the end can return a mongodb::error::Error. But the signature of the main is a std::io::Result<()>, which is an implied Result<(), std::io::Error>. The only error type it can accept is an io::Error, not a mongodb::Error.

It looks like all the functions you are escaping might return this mongodb::error::Error, so you can try to change the main signature to such a result: Result<(). mongodb::error::Error>. But I would recommend you do proper error handling on those potential errors, as this is your main().

Solution

Change those ? to .expect("Some error message"); at least. The program will still crash, but it will crash in a way that is meaningful to you.

Pato Sandaña
  • 519
  • 5
  • 14
LotB
  • 461
  • 4
  • 10