wordval-core 1.0.8

Wordval framework core: app lifecycle, plugin system, error handling, unified response types
Documentation
//! 错误标识与消息注册表
//!
//! 框架所有内置错误文本均通过此注册表查找,用户可在应用启动时调用
//! [`register`] / [`register_all`] 覆盖默认文案,实现错误提示的自定义与国际化。
//!
//! # 示例
//!
//! ```ignore
//! use wordval_core::{ErrorCode, register_error_message, register_error_messages};
//!
//! // 覆盖单个
//! register_error_message(ErrorCode::Internal, "系统开小差了,请稍后再试");
//!
//! // 批量覆盖
//! register_error_messages([
//!     (ErrorCode::Ok, "成功"),
//!     (ErrorCode::Unauthorized, "请先登录"),
//! ]);
//!
//! // 自定义业务码
//! register_error_message(10001, "用户名已存在");
//! ```

use std::collections::HashMap;
use std::sync::OnceLock;

use parking_lot::RwLock;

// ──── ErrorCode 枚举 ──────────────────────────────────────

/// 框架内置错误码枚举
///
/// 每个变体对应一个 HTTP 业务码(`i32`)和默认提示文本。
/// 通过 [`error_message_of`] 可获取当前注册表中的文本(用户可覆盖)。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(i32)]
pub enum ErrorCode {
    /// 成功
    Ok = 200,
    /// 400 客户端请求参数错误
    BadRequest = 400,
    /// 401 未授权 / 未登录
    Unauthorized = 401,
    /// 403 权限不足
    Forbidden = 403,
    /// 404 资源不存在
    NotFound = 404,
    /// 405 请求方法不允许
    MethodNotAllowed = 405,
    /// 409 资源冲突
    Conflict = 409,
    /// 422 请求语义错误(如字段校验失败)
    UnprocessableEntity = 422,
    /// 429 请求频率超限
    TooManyRequests = 429,
    /// 500 服务器内部错误
    Internal = 500,
    /// 503 服务暂时不可用
    ServiceUnavailable = 503,
}

impl ErrorCode {
    /// 返回该错误码的默认提示文本(未注册时的回退值)
    pub fn default_message(self) -> &'static str {
        match self {
            ErrorCode::Ok => "ok",
            ErrorCode::BadRequest => "请求参数错误",
            ErrorCode::Unauthorized => "未授权,请先登录",
            ErrorCode::Forbidden => "权限不足",
            ErrorCode::NotFound => "资源不存在",
            ErrorCode::MethodNotAllowed => "请求方法不允许",
            ErrorCode::Conflict => "资源冲突",
            ErrorCode::UnprocessableEntity => "请求语义错误",
            ErrorCode::TooManyRequests => "请求过于频繁",
            ErrorCode::Internal => "服务器内部错误",
            ErrorCode::ServiceUnavailable => "服务暂时不可用",
        }
    }

    /// 对应的 HTTP 状态码(u16)
    pub fn http_status(self) -> u16 {
        self as u16
    }

    /// 尝试从 i32 还原 ErrorCode(仅框架预定义的码值可还原)
    pub fn from_i32(code: i32) -> Option<Self> {
        match code {
            200 => Some(ErrorCode::Ok),
            400 => Some(ErrorCode::BadRequest),
            401 => Some(ErrorCode::Unauthorized),
            403 => Some(ErrorCode::Forbidden),
            404 => Some(ErrorCode::NotFound),
            405 => Some(ErrorCode::MethodNotAllowed),
            409 => Some(ErrorCode::Conflict),
            422 => Some(ErrorCode::UnprocessableEntity),
            429 => Some(ErrorCode::TooManyRequests),
            500 => Some(ErrorCode::Internal),
            503 => Some(ErrorCode::ServiceUnavailable),
            _ => None,
        }
    }

    /// 所有预定义错误码(用于注册表初始化)
    const ALL: [ErrorCode; 11] = [
        ErrorCode::Ok,
        ErrorCode::BadRequest,
        ErrorCode::Unauthorized,
        ErrorCode::Forbidden,
        ErrorCode::NotFound,
        ErrorCode::MethodNotAllowed,
        ErrorCode::Conflict,
        ErrorCode::UnprocessableEntity,
        ErrorCode::TooManyRequests,
        ErrorCode::Internal,
        ErrorCode::ServiceUnavailable,
    ];
}

impl From<ErrorCode> for i32 {
    fn from(code: ErrorCode) -> i32 {
        code as i32
    }
}

impl std::fmt::Display for ErrorCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", *self as i32)
    }
}

// ──── 全局注册表 ──────────────────────────────────────────

static REGISTRY: OnceLock<RwLock<HashMap<i32, String>>> = OnceLock::new();

/// 获取注册表引用(首次访问时以默认值初始化)
fn registry() -> &'static RwLock<HashMap<i32, String>> {
    REGISTRY.get_or_init(|| {
        let mut map = HashMap::with_capacity(ErrorCode::ALL.len());
        for code in ErrorCode::ALL {
            map.insert(code as i32, code.default_message().to_string());
        }
        RwLock::new(map)
    })
}

// ──── 公开 API ────────────────────────────────────────────

/// 注册 / 覆盖错误码对应的提示文本
///
/// 支持任意 `i32` 业务码,不限于 [`ErrorCode`] 预定义值。
/// 通常在应用启动时(`main` 函数中)调用。
///
/// # 示例
///
/// ```ignore
/// use wordval_core::error_registry::register;
///
/// register(500, "系统开小差了,请稍后再试");
/// register(10001, "用户名已存在");
/// ```
pub fn register(code: impl Into<i32>, msg: impl Into<String>) {
    registry().write().insert(code.into(), msg.into());
}

/// 批量注册 / 覆盖错误码对应的提示文本
///
/// # 示例
///
/// ```ignore
/// use wordval_core::error_registry::{register_all, ErrorCode};
///
/// register_all([
///     (ErrorCode::Ok, "成功"),
///     (ErrorCode::Unauthorized, "请先登录"),
///     (500, "系统繁忙"),
/// ]);
/// ```
pub fn register_all(entries: impl IntoIterator<Item = (impl Into<i32>, impl Into<String>)>) {
    let mut reg = registry().write();
    for (code, msg) in entries {
        reg.insert(code.into(), msg.into());
    }
}

/// 获取错误码对应的提示文本
///
/// 优先返回注册表中的值;若该码从未注册,则回退到:
/// - [`ErrorCode`] 预定义变体的 [`default_message`](ErrorCode::default_message)
/// - 最终回退 `"未知错误"`
pub fn error_message(code: i32) -> String {
    let reg = registry().read();
    if let Some(msg) = reg.get(&code) {
        return msg.clone();
    }
    // 回退:尝试从枚举默认值获取
    ErrorCode::from_i32(code)
        .map(|e| e.default_message().to_string())
        .unwrap_or_else(|| "未知错误".to_string())
}

/// 获取 [`ErrorCode`] 对应的提示文本(便捷版)
///
/// 等价于 `error_message(code as i32)`,但类型更安全。
pub fn error_message_of(code: ErrorCode) -> String {
    error_message(code as i32)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn error_code_roundtrip_from_i32() {
        for code in ErrorCode::ALL {
            let n = code as i32;
            assert_eq!(ErrorCode::from_i32(n), Some(code));
            assert_eq!(code.http_status(), n as u16);
            assert_eq!(i32::from(code), n);
            assert_eq!(code.to_string(), n.to_string());
        }
        assert_eq!(ErrorCode::from_i32(418), None);
    }

    #[test]
    fn default_messages_are_registered() {
        for code in ErrorCode::ALL {
            assert_eq!(error_message_of(code), code.default_message());
        }
    }

    #[test]
    fn register_custom_code() {
        // 使用自定义业务码,不覆盖内置文案,避免并行测试互扰
        register(19_001, "用户名已存在");
        assert_eq!(error_message(19_001), "用户名已存在");
        assert_eq!(error_message(19_002), "未知错误");
    }

    #[test]
    fn register_all_batch() {
        register_all([
            (19_101, "A"),
            (19_102, "B"),
            (ErrorCode::Ok as i32 + 19_000, "C"),
        ]);
        assert_eq!(error_message(19_101), "A");
        assert_eq!(error_message(19_102), "B");
        assert_eq!(error_message(19_200), "C");
    }

    #[test]
    fn unknown_code_falls_back_to_unknown() {
        assert_eq!(error_message(-1), "未知错误");
        assert_eq!(error_message(999_999), "未知错误");
    }
}