首页 > 解决方案 > 当函数输出被宏修复时传播不同的错误

问题描述

我是 rust 新手,在传播不同的错误类型(在本例中来自 actix 和 sqlx)时遇到错误。

我看到类似的问题可以通过将函数的返回更改为适当的类型来解决,或者更改为这些问题中不同可能错误的枚举:

但在这种情况下,我似乎因为宏而不得不保持相同的结果#[actix_web::main],所以这似乎不是一个选择。

在这种情况下,解决办法是什么?我尝试替换-> std::io::Result<()>-> anyhow::Result<()>,但出现类型不匹配的错误。我也用 实现了我自己的枚举thiserror,但发生了同样的错误。

我的代码是下一个:

use actix_web::{App, HttpServer};
use sqlx;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // The trailing `?` here is causing the error below
    let db_pool = sqlx::SqlitePool::connect("sqlite://mydb.db").await?;

    HttpServer::new(move || {
        App::new()
            .data(db_pool.clone())
    })
    .bind(("127.0.0.1", 7000))?
    .run()
    .await
}

这是我得到的错误:

$ cargo run
   Compiling failing_example v0.1.0 (/home/mgarcia/src/isyourplan-backend/bug_minimal)
error[E0277]: `?` couldn't convert the error to `std::io::Error`
 --> src/main.rs:6:70
  |
6 |     let db_pool = sqlx::SqlitePool::connect("sqlite://mydb.db").await?;
  |                                                                      ^ the trait `From<sqlx::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 implementations were found:
            <std::io::Error as From<ErrorKind>>
            <std::io::Error as From<IntoInnerError<W>>>
            <std::io::Error as From<NulError>>
            <std::io::Error as From<brotli2::raw::Error>>
          and 12 others
  = note: required by `from`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.
error: could not compile `failing_example`

To learn more, run the command again with --verbose.

如果它有用,这是我的Cargo.toml

[package]
name = "failing_example"
version = "0.1.0"
authors = ["me"]
edition = "2018"

[dependencies]
actix-web = "3"
sqlx = { version = "0.5", features = ["runtime-actix-rustls", "sqlite"] }

标签: rustactix-webrust-actixrust-sqlx

解决方案


推荐阅读