use super::*;
impl NotLoginException {
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
login_type: String::new(),
}
}
pub fn with_login_type(mut self, login_type: impl Into<String>) -> Self {
self.login_type = login_type.into();
self
}
}
impl std::fmt::Display for NotLoginException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "未登录: {}", self.message)
}
}
impl std::error::Error for NotLoginException {}
impl GarrisonException {
pub fn new(code: i32, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
login_type: 0,
token_value: None,
login_id: None,
extras: HashMap::new(),
}
}
pub fn with_token(mut self, token: impl Into<String>) -> Self {
self.token_value = Some(token.into());
self
}
pub fn with_login_id(mut self, login_id: i64) -> Self {
self.login_id = Some(login_id);
self
}
pub fn with_login_type(mut self, login_type: i32) -> Self {
self.login_type = login_type;
self
}
pub fn with_extra(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.extras.insert(key.into(), value.into());
self
}
pub fn build(self) -> Self {
self
}
}
impl From<GarrisonException> for GarrisonError {
fn from(ex: GarrisonException) -> Self {
GarrisonError::Exception(ex)
}
}
impl From<GarrisonError> for GarrisonException {
fn from(err: GarrisonError) -> Self {
match err {
GarrisonError::Exception(ex) => ex,
GarrisonError::NotLogin(msg) => GarrisonException::new(-1, msg),
GarrisonError::InvalidToken(msg) => GarrisonException::new(-1, msg),
GarrisonError::ExpiredToken(msg) => GarrisonException::new(-1, msg),
GarrisonError::NotPermission(msg) => GarrisonException::new(-2, msg),
GarrisonError::NotRole(msg) => GarrisonException::new(-2, msg),
GarrisonError::FirewallBlocked(msg) => GarrisonException::new(-2, msg),
other => GarrisonException::new(500, other.to_string()),
}
}
}
impl std::fmt::Display for GarrisonException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "业务异常[{}]: {}", self.code, self.message)
}
}
#[cfg(feature = "web-axum")]
impl axum::response::IntoResponse for GarrisonException {
fn into_response(self) -> axum::response::Response {
use axum::http::StatusCode;
tracing::error!(exception = ?self, "garrison exception");
let status = match self.code {
-1 => StatusCode::UNAUTHORIZED,
-2 => StatusCode::FORBIDDEN,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
let body = axum::Json(serde_json::json!({
"code": self.code,
"message": self.message,
"extras": self.extras,
}));
(status, body).into_response()
}
}