Skip to main content

alun_core/
error.rs

1use std::fmt;
2
3/// 框架统一错误类型
4///
5/// 所有模块皆通过此类型返回错误,是 alun 生态的错误"语言"。
6/// 支持从 `std::io::Error`、`String`、`&str`、`ApiError` 自动转换。
7///
8/// # 示例
9///
10/// ```ignore
11/// fn load_config() -> alun_core::Result<AppConfig> {
12///     Err(alun_core::Error::Config("config.toml 格式错误".into()))
13/// }
14/// ```
15#[derive(Debug)]
16pub enum Error {
17    /// 配置加载或解析错误(如 TOML 格式错误、必填字段缺失)
18    Config(String),
19    /// 插件生命周期错误(携带插件名和底层错误源)
20    Plugin {
21        /// 出错的插件名称
22        name: String,
23        /// 底层错误源
24        source: Box<dyn std::error::Error + Send + Sync>,
25    },
26    /// 服务器启动或运行失败(如端口被占用)
27    Server(String),
28    /// IO 操作错误(如文件读写失败、网络故障)
29    Io(std::io::Error),
30    /// 模板渲染错误
31    Template(String),
32    /// 通用业务错误消息
33    Msg(String),
34}
35
36impl fmt::Display for Error {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        match self {
39            Error::Config(msg) => write!(f, "配置错误: {msg}"),
40            Error::Plugin { name, source } => write!(f, "插件 [{name}] 错误: {source}"),
41            Error::Server(msg) => write!(f, "服务器错误: {msg}"),
42            Error::Io(e) => write!(f, "IO 错误: {e}"),
43            Error::Template(msg) => write!(f, "模板错误: {msg}"),
44            Error::Msg(msg) => write!(f, "{msg}"),
45        }
46    }
47}
48
49impl std::error::Error for Error {
50    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
51        match self {
52            Error::Io(e) => Some(e),
53            Error::Plugin { source, .. } => Some(source.as_ref()),
54            _ => None,
55        }
56    }
57}
58
59impl From<std::io::Error> for Error {
60    fn from(e: std::io::Error) -> Self {
61        Error::Io(e)
62    }
63}
64
65impl From<String> for Error {
66    fn from(s: String) -> Self {
67        Error::Msg(s)
68    }
69}
70
71impl From<&str> for Error {
72    fn from(s: &str) -> Self {
73        Error::Msg(s.to_string())
74    }
75}
76
77impl From<crate::api::ApiError> for Error {
78    fn from(e: crate::api::ApiError) -> Self {
79        Error::Msg(e.msg)
80    }
81}
82
83/// 框架统一 Result 类型
84///
85/// `Ok(T)` 表示成功,`Err(Error)` 表示框架内任意模块的错误。
86/// 所有公开 API 的返回值均使用此别名。
87pub type Result<T> = std::result::Result<T, Error>;