ResError实现StdError特质

This commit is contained in:
liyunjia 2024-05-23 21:55:23 +08:00
parent 638226a22e
commit b3ffac651b
4 changed files with 84 additions and 70 deletions

View File

@ -5,5 +5,4 @@ pub mod resp;
pub mod middleware; pub mod middleware;
pub mod token; pub mod token;
pub mod cache; pub mod cache;
pub mod social; pub mod social;
pub mod errors;

View File

@ -90,7 +90,7 @@ async fn drain_body(request: Request, next: Next) -> Result<(Response, Option<St
Ok(v) => v.to_bytes(), Ok(v) => v.to_bytes(),
Err(err) => { Err(err) => {
tracing::error!(error = ?err, "err parse request body"); tracing::error!(error = ?err, "err parse request body");
return Err(ResErr::ErrSystem(None)); return Err(ResErr::default());
} }
}; };

View File

@ -112,68 +112,83 @@ impl IntoResponse for ResErr {
} }
} }
// impl Display for ResErr { impl Display for ResErr {
// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// // write!(f, "{:?}", self.message) // write!(f, "{:?}", self.message)
// match self { match self {
// Error(value, message) => write!(f, "{} - {:?}", value, message), Error(value, message) => write!(f, "{} - {:?}", value, message),
// ErrParams(message) ErrParams(message)
// | ErrAuth(message) | ErrAuth(message)
// | ErrPerm(message) | ErrPerm(message)
// | ErrNotFound(message) | ErrNotFound(message)
// | ErrSystem(message) | ErrSystem(message)
// | ErrData(message) | ErrData(message)
// | ErrService(message) | ErrService(message)
// | ErrSocial(message) => write!(f, "{:?}", message), | ErrSocial(message) => write!(f, "{:?}", message),
// } }
// } }
// } }
// impl StdError for ResErr { impl StdError for ResErr {
// fn cause(&self) -> Option<&dyn StdError> { fn source(&self) -> Option<&(dyn StdError + 'static)> {
// match self { self.source()
// Error(_, _) => None, }
// ErrParams(_) }
// | ErrAuth(_)
// | ErrPerm(_) impl From<String> for ResErr {
// | ErrNotFound(_) fn from(value: String) -> Self {
// | ErrSystem(_) ErrSystem(Some(value))
// | ErrData(_) }
// | ErrService(_) }
// | ErrSocial(_) => None,
// } impl From<&str> for ResErr {
// } fn from(value: &str) -> Self {
ResErr::from(value.to_string())
// fn source(&self) -> Option<&(dyn StdError + 'static)> { }
// None }
// }
impl Default for ResErr {
// fn description(&self) -> &str { fn default() -> Self {
// match self { ErrSystem(None)
// Error(value, message) => &format!("Error, {} - {}", value, message), }
// ErrParams(message) => &format!("ErrParams, {}", message), }
// ErrAuth(message) => &format!("ErrAuth, {}", message),
// ErrPerm(message) => &format!("ErrPerm, {}", message), impl ResErr {
// ErrNotFound(message) => &format!("ErrNotFound, {}", message), pub fn error<T>(code: i32, msg: T) -> Self where T: Into<String> {
// ErrSystem(message) => &format!("ErrSystem, {}", message), Error(code, msg.into())
// ErrData(message) => &format!("ErrData, {}", message), }
// ErrService(message) => &format!("ErrService, {}", message),
// ErrSocial(message) => &format!("ErrSocial, {}", message), pub fn params<T>(msg: T) -> Self where T: Into<String> {
// } ErrParams(Some(msg.into()))
// } }
// fn provide<'a>(&'a self, request: &mut std::error::Request<'a>) { pub fn auth<T>(msg: T) -> Self where T: Into<String> {
// match self { ErrAuth(Some(msg.into()))
// ResErr::ErrSystem(e) => request.provide_ref(e), }
// ResErr::ErrData(e) => request.provide_ref(e),
// ResErr::ErrService(e) => request.provide_ref(e), pub fn perm<T>(msg: T) -> Self where T: Into<String> {
// ResErr::ErrSocial(e) => request.provide_ref(e), ErrPerm(Some(msg.into()))
// ResErr::ErrNotFound(e) => request.provide_ref(e), }
// ResErr::ErrPerm(e) => request.provide_ref(e),
// ResErr::ErrAuth(e) => request.provide_ref(e), pub fn not_found<T>(msg: T) -> Self where T: Into<String> {
// ResErr::ErrParams(e) => request.provide_ref(e), ErrNotFound(Some(msg.into()))
// ResErr::Error(_, e) => request.provide_ref(e), }
// }
// } pub fn system<T>(msg: T) -> Self where T: Into<String> {
ErrSystem(Some(msg.into()))
}
pub fn data<T>(msg: T) -> Self where T: Into<String> {
ErrData(Some(msg.into()))
}
pub fn service<T>(msg: T) -> Self where T: Into<String> {
ErrService(Some(msg.into()))
}
pub fn social<T>(msg: T) -> Self where T: Into<String> {
ErrSocial(Some(msg.into()))
}
}
pub type ResResult<T> = std::result::Result<T, ResErr>; pub type ResResult<T> = std::result::Result<T, ResErr>;

View File

@ -5,7 +5,7 @@ use jsonwebtoken::{decode, errors::ErrorKind, Algorithm, DecodingKey, TokenData,
use reqwest::Client; use reqwest::Client;
use serde_json::Value; use serde_json::Value;
use crate::{errors::MessageError, resp::response::ResErr}; use crate::resp::response::ResErr;
use super::SocialResult; use super::SocialResult;
@ -122,12 +122,12 @@ async fn verify_id_token(id_token: &str) -> SocialResult<GoogleJwtProfile> {
// 检查是否找到了有效的kid // 检查是否找到了有效的kid
if kid.is_none() { if kid.is_none() {
return Err(Box::new(MessageError::from("校验Token失败,未找到有效的kid"))); return Err(Box::new(ResErr::social("校验Token失败,未找到有效的kid")));
} }
let kid = kid.unwrap(); let kid = kid.unwrap();
// 根据kid找到正确的公钥 // 根据kid找到正确的公钥
let key = public_keys.get(&kid).ok_or_else(|| Box::new(MessageError::from("校验Token失败,未找到正确的公钥")))?; let key = public_keys.get(&kid).ok_or_else(|| Box::new(ResErr::social("校验Token失败,未找到正确的公钥")))?;
// 验证Token // 验证Token
let mut validation: Validation = Validation::new(Algorithm::RS256); let mut validation: Validation = Validation::new(Algorithm::RS256);
@ -140,7 +140,7 @@ async fn verify_id_token(id_token: &str) -> SocialResult<GoogleJwtProfile> {
// 校验有效期 // 校验有效期
if google_jwt_profile.exp < Utc::now().timestamp() { if google_jwt_profile.exp < Utc::now().timestamp() {
return Err(Box::new(MessageError::from("校验Token失败,token有效期无效"))); return Err(Box::new(ResErr::social("校验Token失败,token有效期无效")));
} }
// 校验签发时间 // 校验签发时间
// if google_jwt_profile.iat > Utc::now().timestamp() { // if google_jwt_profile.iat > Utc::now().timestamp() {
@ -150,7 +150,7 @@ async fn verify_id_token(id_token: &str) -> SocialResult<GoogleJwtProfile> {
// } // }
// 校验iss字段 // 校验iss字段
if google_jwt_profile.iss != "accounts.google.com" && google_jwt_profile.iss != "https://accounts.google.com" { if google_jwt_profile.iss != "accounts.google.com" && google_jwt_profile.iss != "https://accounts.google.com" {
return Err(Box::new(MessageError::from("校验Token失败,token签发人非法"))); return Err(Box::new(ResErr::social("校验Token失败,token签发人非法")));
} }
Ok(google_jwt_profile) Ok(google_jwt_profile)