Rust 异步编程错误处理:从原理到实战
异步错误的本质与分类
在同步编程中,错误通常通过 Result<T, E> 返回,程序会阻塞线程直到操作完成。而在异步场景下,结果是一个 Future<Output = Result<T, E>>,任务暂停而非阻塞线程,这意味着我们需要更精细地管理错误传播和生命周期。
同步与异步的差异
同步代码示例如下,读取文件时会直接阻塞当前线程:
use std::fs::File;
use std::io::Read;
fn read_file_sync() -> Result<String, std::io::Error> {
let mut file = File::open("test.txt")?;
let mut content = String::new();
file.read_to_string(&mut content)?;
Ok(content)
}
fn main() {
match read_file_sync() {
Ok(content) => println!("File content: {}", content),
Err(e) => println!("Error reading file: {}", e),
}
}
换成异步后,使用 tokio 的 await 关键字,任务会在 IO 等待时让出 CPU:
use tokio::fs::File;
use tokio::io::AsyncReadExt;
async fn read_file_async() -> Result<String, std::io::Error> {
let = File::().?;
= ::();
file.(& content).?;
(content)
}
() {
(). {
(content) => (, content),
(e) => (, e),
}
}


