在 actix-web 的主要方法中处理错误的最佳方法是什么?

问题描述

有没有办法处理actix-web中main方法中的错误

我有以下代码,如您所见,该函数中有三个地方可能会发生恐慌:对 DATABASE_URL 环境变量的引用、连接池的创建和模板引擎 (tera) 的初始化。

>
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    dotenv().ok();
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set.");
    let manager = ConnectionManager::<PgConnection>::new(database_url);
    let pool = Pool::builder().build(manager).expect("Failed to create connection pool.");

    HttpServer::new(move || {
        let tera = tera::new("templates/**/*").unwrap();
        App::new()
            .data(pool.clone())
            .data(tera)
            .route("/",web::get().to(index))
    })
    .bind("127.0.0.1:8000")?
    .run()
    .await
}

因此,我尝试更改该函数的返回类型并使用先前定义的 Enum 来处理这些错误

async fn main() -> Result<HttpServer,ServerError> {
    dotenv().ok();
    let database_url = std::env::var("DATABASE_URL")?;
    let manager = ConnectionManager::<PgConnection>::new(database_url);
    let pool = Pool::builder().build(manager)?;

    HttpServer::new(move || {
        let tera = tera::new("templates/**/*")?;
        App::new()
            .data(pool.clone())
            .data(tera)
            .route("/",web::get().to(index))
    })
    .bind("127.0.0.1:8000")?
    .run()
    .await
}

但编译器显示此消息:

[Running 'cargo run']

error[E0107]: missing generics for struct `HttpServer`
    |
    | async fn main() -> Result<HttpServer,ServerError> {
    |                           ^^^^^^^^^^ expected 4 type arguments
    |

note: struct defined here,with 4 type parameters: `F`,`I`,`S`,`B`

    |
    | pub struct HttpServer<F,I,S,B>
    |            ^^^^^^^^^^ -  -  -  -
help: use angle brackets to add missing type arguments
    |
    | async fn main() -> Result<HttpServer<F,B>,ServerError> {
    |                                     ^^^^^^^^^^^^

error: aborting due to prevIoUs error

For more information about this error,try `rustc --explain E0107`.
error: Could not compile

在这里可以遵循的最佳行动方案是什么?我应该在 main 方法中处理这种错误吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)