微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决在 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 举报,一经查实,本站将立刻删除。