gpt4 book ai didi

error-handling - 使用 Box 装箱后如何处理不同的错误类型?

转载 作者:行者123 更新时间:2023-11-29 08:28:46 30 4
gpt4 key购买 nike

为了更好地处理错误并防止重复太多代码,我正在实现 ? , 运算符返回 Result<bool, Box<error::Error>>这样我就可以 match错误一次而不是多次。

我使用多个 match 更改了以下代码是:

fn example(pool: mysql::Pool) {
let now = match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
Ok(n) => n.as_secs(),
Err(_) => panic!("SystemTime before UNIX EPOCH!"),
};

// create table
match pool.prep_exec("CREATE TABLE IF NOT EXISTS dbpulse_rw (id INT NOT NULL, t INT(11) NOT NULL, PRIMARY KEY(id))", ()) {
Ok(_) => (),
Err(e) => {
eprintln!("{}", e);
return;
}
}

// write into table
let mut stmt = match pool
.prepare("INSERT INTO dbpulse_rw (id, t) VALUES (1, ?) ON DUPLICATE KEY UPDATE t=?")
{
Ok(stmt) => stmt,
Err(e) => {
eprintln!("{}", e);
return;
}
};

match stmt.execute((now, now)) {
Ok(_) => (),
Err(mysql::Error::IoError(e)) => {
eprintln!("IoError: {}", e);
// send alert
return;
}
Err(e) => {
eprintln!("{}", e);
return;
}
}

let items = match pool.prep_exec("SELECT t FROM dbpulse_rw WHERE id=1", ()) {
Ok(n) => n,
Err(mysql::Error::IoError(e)) => {
eprintln!("IoError: {}", e);
//send_alert
return;
}
Err(e) => {
eprintln!("{}", e);
return;
}
};
for row in items {
let pool = pool.clone();
let rs = mysql::from_row::<u64>(row.unwrap());
if now != rs {
// send alert
}
assert_eq!(now, rs);
}
}

使用?运算符(operator):

fn example(pool: mysql::Pool) -> Result<bool, Box<error::Error>> {
let n = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?;
let now = n.as_secs();

// create table
pool.prep_exec("CREATE TABLE IF NOT EXISTS dbpulse_rw (id INT NOT NULL, t INT(11) NOT NULL, PRIMARY KEY(id))", ())?;

// write into table
let mut stmt = pool
.prepare("INSERT INTO dbpulse_rw (id, t) VALUES (1, ?) ON DUPLICATE KEY UPDATE t=?")?;
stmt.execute((now, now))?;

pool.prep_exec("SELECT t FROM dbpulse_rw WHERE id=1", ())
.map(|items| {
for row in items {
match row {
Ok(row) => {
let rs = mysql::from_row::<u64>(row);
if now != rs {
// send alert
}
}
Err(e) => println!("{}", e),
}
}
})?;

Ok(true)
}

我现在想做的是 match基于错误,超时或查询错误,或其他错误类型。我正在这样创建 MySQL 池:

let mut opts = mysql::OptsBuilder::from_opts(dsn);
opts.stmt_cache_size(0);
opts.read_timeout(Some(Duration::new(3, 0)));
opts.write_timeout(Some(Duration::new(3, 0)));
let pool = mysql::Pool::new_manual(1, 5, opts).expect("Could not connect to MySQL");

如果查询时间超过 3 秒,它将返回 mysql::Error::IoError我想区分其他可能的错误,到目前为止我已经尝试过:

fun run_example() {
match example() {
Ok(_) => (),
Err(mysql::Error::IoError(e)) => {
eprintln!("IoError: {}", e);
// send alert
return;
}
Err(e) => {
eprintln!("{}", e);
return;
}
}
}

但是我遇到了类型不匹配的错误:

expected struct `std::boxed::Box`, found enum `mysql::error::Error`

关于如何实现这个的任何提示或更好的想法?

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com