#error #utility-macro #enums #utility #macro #io-error

wrapping_error

用于包装错误的反模板化软件包

1 个不稳定版本

0.1.0 2023年7月20日

#11#utility-macro

MIT 许可证

6KB

wrapping_error

用于包装错误的反模板化软件包。

本软件包只导出一个项目:宏 wrapping_error。使用 wrapping_error 宏,你可以编写这个

use std::{env::VarError, io};

use wrapping_error::wrapping_error;

wrapping_error!(pub(crate) AppDataError {
    Var(VarError) => "could not get $HOME environment variable",
    Io(io::Error) => "failed to read/write app data",
    Postcard(postcard::Error) => "failed to serialize/deserialize app data",
});

然后得到这个

use std::{fmt, error, env::VarError, io};

#[derive(Debug)]
pub(crate) enum AppDataError {
    Var(VarError),
    Io(io::Error),
    Postcard(postcard::Error),
}

impl fmt::Display for AppDataError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Self::Var(..) => write!(f, "could not get $HOME environment variable"),
            Self::Io(..) => write!(f, "failed to read/write app data"),
            Self::Postcard(..) => write!(f, "failed to serialize/deserialize app data"),
            ref err => err.fmt(f),
        }
    }
}

impl error::Error for AppDataError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match *self {
            ref err => Some(err),
        }
    }
}

impl From<VarError> for AppDataError {
    fn from(err: VarError) -> Self {
        Self::Var(err)
    }
}

impl From<io::Error> for AppDataError {
    fn from(err: io::Error) -> Self {
        Self::Io(err)
    }
}

impl From<postcard::Error> for AppDataError {
    fn from(err: postcard::Error) -> Self {
        Self::Postcard(err)
    }
}

无运行时依赖