I am trying to use anyhow::Result
instead of std::io::Result
in an actix-web service. This is because I want to be able to use the "?" operator instead of .expect
/.map_err
. However, I am getting an error message:
error[E0277]: `?` couldn't convert the error to `std::io::Error`
--> backend/src/services/get_movies_count.rs:10:48
|
10 | let mut database = app_state.database.get()?;
| ^ the trait `std::convert::From<r2d2::Error>` is not implemented for `std::io::Error`
|
= note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
= help: the following other types implement trait `std::convert::From<T>`:
<std::io::Error as std::convert::From<ErrorKind>>
<std::io::Error as std::convert::From<IntoInnerError<W>>>
<std::io::Error as std::convert::From<JoinError>>
<std::io::Error as std::convert::From<NulError>>
<std::io::Error as std::convert::From<flate2::mem::CompressError>>
<std::io::Error as std::convert::From<flate2::mem::DecompressError>>
<std::io::Error as std::convert::From<getrandom::error::Error>>
<std::io::Error as std::convert::From<httpdate::Error>>
and 4 others
= note: required for `Result<String, std::io::Error>` to implement `FromResidual<Result<Infallible, r2d2::Error>>`
For more information about this error, try `rustc --explain E0277`.
Here is the actix-web service code:
use crate::AppState;
use anyhow::Result;
use actix_web::{get, web::Data};
#[get("movies/count")]
async fn get_movies_count(app_state: Data<AppState>) -> Result<String> {
let database = app_state.database.get()?;
Ok("Hi".into())
}
main.rs
use std::env::var;
use anyhow::Result;
use actix_web::{HttpServer, App, web::Data};
use diesel::{r2d2::{ConnectionManager, Pool}, SqliteConnection};
use services::{
get_movies_count::get_movies_count,
};
mod schema;
mod models;
mod services;
#[derive(Clone)]
struct AppState {
database: Pool<ConnectionManager<SqliteConnection>>
}
#[actix_web::main]
async fn main() -> Result<()> {
dotenv::dotenv()?;
let manager = ConnectionManager::<SqliteConnection>::new(var("DATABASE_URL")?);
let pool = Pool::builder().build(manager)?;
let app_state = AppState {
database: pool
};
HttpServer::new(
move || {
App::new()
.app_data(Data::new(app_state.clone()))
.service(get_movies_count)
}
)
.bind(
(
var("HOST")?,
var("API_PORT")?.parse()?
)
)?
.run()
.await?;
Ok(())
}