rust - 当函数输出被宏修复时传播不同的错误
问题描述
我是 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"] }
解决方案
推荐阅读
- sql - 如何连接sql数据库和ignite集群来同步数据?
- excel - 仅替换excel中单元格范围内的数字
- javascript - 有没有办法可以将路线的结果作为另一条路线中的字段传递?
- kotlin - 如何修复分配不是表达式 kotlin,只允许表达式
- javascript - socket.on 在 io.sockets.on('connection,..) 之外不起作用
- javascript - 如何使用 JQuery 停止使用关闭按钮重定向
- python - Python pip install 找不到模块
- java - 在 Mono 上使用 elapsed() 函数?
- c - 如何检查 CLI 定义的 MACRO (-DMACRO=) 是否已定义
- swiftui - 更改选项卡式视图栏颜色 SwiftUI