use std::fmt;
use xbw::all::AxiosError;
use xbw::crypt::{base64::DecodeError, hex};
#[derive(Debug)]
pub enum BotError {
Http(AxiosError),
Api {
ret: i64,
message: String,
},
Crypto(String),
Io(std::io::Error),
InvalidData(String),
Timeout(String),
Other(String),
}
impl fmt::Display for BotError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
BotError::Http(e) => write!(f, "HTTP 错误: {}", e),
BotError::Api { ret, message } => {
write!(f, "API 错误 (ret={}): {}", ret, message)
}
BotError::Crypto(msg) => write!(f, "加解密错误: {}", msg),
BotError::Io(e) => write!(f, "I/O 错误: {}", e),
BotError::InvalidData(msg) => write!(f, "数据格式错误: {}", msg),
BotError::Timeout(msg) => write!(f, "超时: {}", msg),
BotError::Other(msg) => write!(f, "{}", msg),
}
}
}
impl std::error::Error for BotError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
BotError::Http(e) => Some(e),
BotError::Io(e) => Some(e),
_ => None,
}
}
}
impl From<AxiosError> for BotError {
fn from(e: AxiosError) -> Self {
BotError::Http(e)
}
}
impl From<std::io::Error> for BotError {
fn from(e: std::io::Error) -> Self {
BotError::Io(e)
}
}
impl From<DecodeError> for BotError {
fn from(e: DecodeError) -> Self {
BotError::InvalidData(format!("Base64 解码失败: {}", e))
}
}
impl From<hex::FromHexError> for BotError {
fn from(e: hex::FromHexError) -> Self {
BotError::InvalidData(format!("Hex 解码失败: {}", e))
}
}
impl BotError {
pub fn other(msg: impl Into<String>) -> Self {
BotError::Other(msg.into())
}
pub fn crypto(msg: impl Into<String>) -> Self {
BotError::Crypto(msg.into())
}
pub fn api(ret: i64, message: impl Into<String>) -> Self {
BotError::Api {
ret,
message: message.into(),
}
}
pub fn timeout(msg: impl Into<String>) -> Self {
BotError::Timeout(msg.into())
}
pub fn invalid_data(msg: impl Into<String>) -> Self {
BotError::InvalidData(msg.into())
}
}
pub type BotResult<T> = Result<T, BotError>;