anyhow 是一个 Rust 库,用于简化错误处理。虽然它非常灵活且易于使用,但不幸的是,你不能直接自定义 anyhow 库本身。然而,你可以通过以下方法根据自己的需求定制错误处理:
- 创建自定义错误类型:你可以创建一个自定义错误类型,实现 std::error::Error和std::fmt::Displaytrait。然后,你可以使用这个自定义错误类型替换anyhow的默认错误类型。
use std::fmt;
use std::error;
#[derive(Debug)]
pub enum CustomError {
    IoError(std::io::Error),
    ParseError(std::num::ParseIntError),
    // 其他自定义错误类型
}
impl fmt::Display for CustomError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            CustomError::IoError(err) => write!(f, "IO error: {}", err),
            CustomError::ParseError(err) => write!(f, "Parse error: {}", err),
            // 其他自定义错误类型的格式化
        }
    }
}
impl error::Error for CustomError {}
// 为其他错误类型实现 From trait
impl From<std::io::Error> for CustomError {
    fn from(err: std::io::Error) -> CustomError {
        CustomError::IoError(err)
    }
}
impl From<std::num::ParseIntError> for CustomError {
    fn from(err: std::num::ParseIntError) -> CustomError {
        CustomError::ParseError(err)
    }
}
- 使用 anyhow与自定义错误类型:在你的代码中,使用anyhow::Result类型,并在出现错误时返回自定义错误类型。
use anyhow::{Context, Result};
fn read_file_contents(file_path: &str) -> Result<String> {
    std::fs::read_to_string(file_path).context("Failed to read file")
}
fn main() -> Result<()> {
    let contents = read_file_contents("example.txt")?;
    println!("File contents: {}", contents);
    Ok(())
}
这样,你就可以使用自定义错误类型处理错误,同时仍然利用 anyhow 的便利功能。

 便宜VPS测评
便宜VPS测评










