mycommon-utils 0.1.1

common db or redis
Documentation
#[allow(dead_code)]
use serde::{Deserialize, Serialize};
use std::error::Error as StdError;
use std::fmt::{self, Debug, Display};
use std::num::ParseIntError;
use std::string::FromUtf8Error;
use validator::ValidationErrors;

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct Error {
    pub error_code: i32,
    pub error_msg: String,
}

macro_rules! static_errors {
    ($name:ident, $code:expr, $msg:expr) => {
        #[allow(non_snake_case, missing_docs)]
        pub fn $name() -> Error {
            Error::create($code, $msg)
        }
    };
}

#[allow(dead_code)]
impl Error {
    pub fn create(code: i32, msg: &str) -> Self {
       let err =  Self {
            error_code: code,
            error_msg: msg.to_string(),
        };
        return err;
    }
    pub fn new() -> Self {
        let err =  Self {
            error_code: 500,
            error_msg: "".to_string(),
        };
        return err;
    }
    pub fn error_code(mut self, code: i32) -> Self {
        self.error_code = code;
        self
    }
    pub fn error_msg(mut self, msg: String) -> Self {
        self.error_msg = msg;
        self
    }
    // 定義錯誤類型數據靜態創建方法

    static_errors!(NotFound, 404, "Not Found");
    static_errors!(ErrorNoPermission, 403, "No permission management \n 沒有權限管理");
    static_errors!(ErrorInternalServer, 500, "Internal Server Error \n 服务器内部错误");
    static_errors!(ErrorRedisConnectError, 6000, "Failed to connect to Redis \n Redis 连接失败");

    static_errors!(ErrorStartTransactionFailed, 6001, "Failed to open transaction \n 開啟事務失敗");
    static_errors!(ErrorCommitTransactionFailed, 6002, "Failed to commit transaction \n 提交事務失敗");
    static_errors!(ErrorParsingPrivateKey, 1406, "Error parsing private key \n 解析私钥错误");
    static_errors!(NotFoundPrivateKey, 1405, "Not Found Private Key \n 没有找到私钥");


    // 创建相关错误
    static_errors!(ErrorCreateFailed, 8000, "Creation operation failed. \n 创建操作失败。");
    static_errors!(ErrorStaffRepeatCreate, 8001, "The current staff member has already been created. \n 当前员工已创建。");
    static_errors!(ErrorAMSCreateStaffFailed, 8002, "Failed to create a staff member in AMS. \n AMS 创建员工失败。");

    // 更新相关错误
    static_errors!(ErrorUpdateFailed, 8003, "Update operation failed. \n 修改操作失败。");
    static_errors!(ErrorAMSUpdateStaffFailed, 8004, "Failed to update a staff member in AMS. \n AMS 更新员工失败。");

    // 删除相关错误
    static_errors!(ErrorDeleteFailed, 8005, "Deletion operation failed. \n 删除操作失败。");
    static_errors!(ErrorDeleteStaffCardFailed, 8006, "Failed to delete the staff member's card. Please contact the administrator! \n 删除人员卡失败,请联系管理员!");
    static_errors!(ErrorDeleteStaffFailed, 8007, "Failed to delete the staff member's roles. Please contact the administrator! \n 删除人员权限失败,请联系管理员!");

    // 查询相关错误
    static_errors!(ErrorQueryFailed, 8008, "Query operation failed. \n 查询操作失败。");
    //远程请求失败
    static_errors!(ErrorRemoteRequestFailed, 8009, "Remote request failed. \n 远程请求失败。");
    //调用AMS设备状态接口失败
    static_errors!(ErrorAMSDeviceStatusInterface, 8010, "Failed to call the AMS device status interface. \n 调用 AMS 设备状态接口失败。");

    // 同步相关错误
    static_errors!(ErrorAMSSyncCommandTypeInterface, 8011, "Failed to synchronize the AMS command type interface. \n 同步 AMS 命令类型接口失败。");
    static_errors!(ErrorAMSDeviceSyncInterface, 8012, "Failed to synchronize the AMS device interface. \n 同步 AMS 设备接口失败。");
    static_errors!(ErrorAMSDeviceTypeSyncInterface, 8013, "Failed to synchronize the AMS device type interface. \n 同步 AMS 设备类型接口失败。");
    static_errors!(ErrorAMSEventTypeSyncInterface, 8014, "Failed to synchronize the AMS event type interface. \n 同步 AMS 事件类型接口失败。");
    static_errors!(ErrorAMSPermissionSyncInterface, 8015, "Failed to synchronize the AMS permission interface. \n 同步 AMS 权限接口失败。");
    static_errors!(ErrorAMSStatusTypeSyncInterface, 8016, "Failed to synchronize the AMS status type interface. \n 同步 AMS 状态类型失败。");

    // 授权相关错误
    static_errors!(ErrorAMSPersonAuthorFailed, 8017, "Failed to authorize a card for a personnel in the AMS interface. \n AMS 人员授权卡失败。");
    static_errors!(ErrorAMSPersonAuthorRepeat, 8018, "The personnel has already been authorized. Please do not authorize again! \n 人员已授权,请不要重复授权!");
    static_errors!(ErrorAMSPersonAuthorRoleFailed, 8019, "Failed to authorize a role for a personnel in the AMS interface. \n AMS 人员授权角色失败。");

    // 设备相关错误
    static_errors!(ErrorPersonnelDeviceUnauthorized, 8020, "The personnel is not authorized to use the device. \n 人员没有授权使用设备。");
    static_errors!(ErrorAMSDeviceCommandExecution, 8021, "The AMS device failed to execute the command. \n AMS 设备执行命令失败。");

    // 其他错误
    static_errors!(ErrorCardRepeatAssign, 8022, "The current card has already been assigned. \n 当前卡已分配。");
    static_errors!(ErrorCardRepeatStaff, 8023, "The current card has already been assigned to a staff member. \n 当前卡已分配给人员。");
    static_errors!(ErrorAMSUnbindCardFailed, 8024, "Failed to unbind a card in AMS. \n AMS 解绑卡接口失败。");
    static_errors!(ErrorQRCodeGenerateWithoutAuth, 8025, "Without proper authorization, unable to generate a QR code. \n 没有授权,无法生成二维码!");
    static_errors!(ErrorPermissionExpiryConfigMissing, 8026, "Configuration error: The permission expiration time is not configured. \n 配置错误,权限没有配置过期时间!");
    static_errors!(ErrorCardNumberDuplicate, 8027, "The card number is a duplicate. \n 卡号重复。");
    static_errors!(ErrorDoorOpeningTimeRestricted, 8028, "Door opening is not allowed during the current time period. \n 当前时间段不允许开门。");
    //人员有效时间必须设置
    static_errors!(ErrorPersonValidTimeNotSet, 8029, "The person's valid time must be set. \n 人员有效时间必须设置。");
    //失效时间必须晚于生效时间
    static_errors!(ErrorPersonValidTimeInvalid, 8030, "The person's valid time is invalid. \n 人员有效时间无效。");
    //人员没有找到
    static_errors!(ErrorPersonNotFound, 8031, "The person is not found. \n 没有查找到人员信息。");
    //AMS 删除人员权限
    static_errors!(ErrorAMSDeletePermissionFailed, 8032, "Failed to delete a permission in AMS. \n AMS 删除人员权限失败。");
    //增加失败,部门名称已存在
    static_errors!(ErrorDepartmentNameRepeat, 8033, "The department name already exists. \n 部门名称已存在。");
    //增加失败,父节点不存在
    static_errors!(ErrorParentNodeNotExist, 8034, "The parent node does not exist. \n 父节点不存在。");
    //部门停用,不允许新增
    static_errors!(ErrorDepartmentDisable, 8035, "The department is disabled. \n 部门停用,不允许新增。");
    //没有找到数据
    static_errors!(ErrorDataNotFound, 8036, "No data found. \n 没有找到数据。");
    //岗位已分配人员,不允许删除
    static_errors!(ErrorPostHasStaff, 8037, "The post has staff members, and it is not allowed to delete. \n 岗位已分配人员,不允许删除。");



}

impl Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:{}", self.error_code, self.error_msg)
    }
}
impl StdError for Error {}

impl From<&str> for Error {
    fn from(arg: &str) -> Self {
        Error::new().error_msg(arg.to_string())
    }
}

// std::io::Error
impl From<std::io::Error> for Error {
    fn from(arg: std::io::Error) -> Self {
        tracing::error!("std::io::Error:{}",arg.to_string());
        Error::new().error_code(100).error_msg(arg.to_string())
    }
}

// sea_orm 框架的错误
impl From<sea_orm::DbErr> for Error {
    fn from(arg: sea_orm::DbErr) -> Self {
        tracing::error!("sea_orm::DbErr:{}",arg.to_string());
        Error::new().error_code(101).error_msg(arg.to_string())
    }
}

// serde_json 框架的错误
impl From<serde_json::Error> for Error {
    fn from(arg: serde_json::Error) -> Self {
        tracing::error!("serde_json::Error:{}",arg.to_string());
        Error::new().error_code(102).error_msg(arg.to_string())
    }
}

// reqwest 框架的错误
impl From<reqwest::Error> for Error {
    fn from(arg: reqwest::Error) -> Self {
        tracing::error!("reqwest::Error:{}",arg.to_string());
        Error::new().error_code(103).error_msg(arg.to_string())
    }
}


// Redis 框架的错误
impl From<redis::RedisError> for Error {
    fn from(arg: redis::RedisError) -> Self {
        tracing::error!("RedisError:{}",arg.to_string());
        Error::new().error_code(105).error_msg(arg.to_string())
    }
}


// Validator 框架的错误
impl From<ValidationErrors> for Error {
    fn from(arg: ValidationErrors) -> Self {
        tracing::error!("ValidationErrors:{}",arg.to_string());
        Error::new().error_code(106).error_msg(arg.to_string())
    }
}

// 字符串转换为数字失败
impl From<ParseIntError> for Error {
    fn from(arg: ParseIntError) -> Self {
        tracing::error!("ParseIntError:{}",arg.to_string());
        Error::new().error_code(107).error_msg(arg.to_string())
    }
}

// 转为字符串失败
impl From<FromUtf8Error> for Error {
    fn from(arg: FromUtf8Error) -> Self {
        tracing::error!("FromUtf8Error:{}",arg.to_string());
        Error::new().error_code(108).error_msg(arg.to_string())
    }
}