Search code examples
mongodbrustactix-webrust-crates

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


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?


Solution

  • 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.