Skip to content

Commit

Permalink
feat(error): Enhance OssService
Browse files Browse the repository at this point in the history
  • Loading branch information
tu6ge committed Dec 7, 2022
1 parent 7bc42ac commit e74deec
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 27 deletions.
13 changes: 5 additions & 8 deletions src/blocking/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,17 +111,14 @@ pub trait BlockingReqeustHandler {
impl BlockingReqeustHandler for Response {
/// # 收集并处理 OSS 接口返回的错误
fn handle_error(self) -> Result<Response, BuilderError> {
use crate::builder::SUCCESS_STATUS;
use crate::errors::OssService;

let status = self.status();

for item in SUCCESS_STATUS.iter() {
if *item == status {
return Ok(self);
}
if self.status().is_success() {
return Ok(self);
}

Err(OssService::new(&self.text()?).into())
let status = self.status();

Err(OssService::new(&self.text()?, &status).into())
}
}
13 changes: 5 additions & 8 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,21 +159,18 @@ pub trait RequestHandler {
async fn handle_error(self) -> Result<Response, BuilderError>;
}

pub const SUCCESS_STATUS: [u16; 3] = [200, 204, 206];
use crate::errors::OssService;

#[async_trait]
impl RequestHandler for Response {
/// # 收集并处理 OSS 接口返回的错误
async fn handle_error(self) -> Result<Response, BuilderError> {
let status = self.status();

for item in SUCCESS_STATUS.iter() {
if *item == status {
return Ok(self);
}
if self.status().is_success() {
return Ok(self);
}

Err(OssService::new(&self.text().await?).into())
let status = self.status();

Err(OssService::new(&self.text().await?, &status).into())
}
}
24 changes: 15 additions & 9 deletions src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use hmac::digest::crypto_common;
use http::header::ToStrError;
use http::{header::ToStrError, StatusCode};
use std::fmt;
use thiserror::Error;

Expand Down Expand Up @@ -45,12 +44,11 @@ pub enum OssError {
#[error("ParseIntError: {0}")]
ParseIntError(#[from] std::num::ParseIntError),

#[error("hmac InvalidLength: {0}")]
InvalidLength(#[from] crypto_common::InvalidLength),

#[error("FromUtf8Error: {0}")]
FromUtf8Error(#[from] std::string::FromUtf8Error),
// #[error("hmac InvalidLength: {0}")]
// InvalidLength(#[from] crypto_common::InvalidLength),

// #[error("FromUtf8Error: {0}")]
// FromUtf8Error(#[from] std::string::FromUtf8Error),
#[error("aliyun response error: {0}")]
OssService(#[from] OssService),

Expand Down Expand Up @@ -84,9 +82,14 @@ impl OssError {
}
}

/// # 保存并返回 OSS 服务端返回是数据
/// 当服务器返回的状态码不在 200<=x 且 x<300 范围时,则会返回此错误
///
/// 如果解析 xml 格式错误,则会返回默认值,默认值的 status = 200
#[derive(Debug, Error, PartialEq)]
pub struct OssService {
pub code: String,
pub status: StatusCode,
pub message: String,
pub request_id: String,
}
Expand All @@ -95,7 +98,8 @@ impl Default for OssService {
fn default() -> Self {
Self {
code: "Undefined".to_owned(),
message: "parse aliyun response xml error message failed".to_owned(),
status: StatusCode::default(),
message: "Parse aliyun response xml error message failed.".to_owned(),
request_id: "XXXXXXXXXXXXXXXXXXXXXXXX".to_owned(),
}
}
Expand All @@ -105,6 +109,7 @@ impl fmt::Display for OssService {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("OssService")
.field("code", &self.code)
.field("status", &self.status)
.field("message", &self.message)
.field("request_id", &self.request_id)
.finish()
Expand All @@ -113,7 +118,7 @@ impl fmt::Display for OssService {

impl<'a> OssService {
/// 解析 oss 的错误信息
pub fn new(source: &'a str) -> Self {
pub fn new(source: &'a str, status: &StatusCode) -> Self {
let code0 = match source.find("<Code>") {
Some(offset) => offset,
None => return Self::default(),
Expand Down Expand Up @@ -141,6 +146,7 @@ impl<'a> OssService {

Self {
code: (&source[code0 + 6..code1]).to_owned(),
status: status.clone(),
message: (&source[message0 + 9..message1]).to_owned(),
request_id: (&source[request_id0 + 11..request_id1]).to_owned(),
}
Expand Down
8 changes: 6 additions & 2 deletions src/tests/errors.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use http::StatusCode;

use crate::errors::{OssError, OssService};

#[test]
Expand All @@ -8,6 +10,7 @@ fn test_message() {

let oss_err = OssError::OssService(OssService {
code: "OSS_TEST_CODE".to_string(),
status: StatusCode::default(),
message: "foo_msg".to_string(),
request_id: "foo_req_id".to_string(),
});
Expand All @@ -19,13 +22,14 @@ fn test_message() {
fn test_oss_service_fmt() {
let oss_err = OssService {
code: "OSS_TEST_CODE".to_string(),
status: StatusCode::default(),
message: "foo_msg".to_string(),
request_id: "foo_req_id".to_string(),
};

assert_eq!(
format!("{}", oss_err),
"OssService { code: \"OSS_TEST_CODE\", message: \"foo_msg\", request_id: \"foo_req_id\" }"
"OssService { code: \"OSS_TEST_CODE\", status: 200, message: \"foo_msg\", request_id: \"foo_req_id\" }"
.to_string()
);
}
Expand All @@ -43,7 +47,7 @@ fn test_oss_service_new() {
<ServerTime>2022-09-04T08:11:37.000Z</ServerTime>
</Error>
"#;
let service = OssService::new(content);
let service = OssService::new(content, &StatusCode::default());
assert_eq!(service.code, format!("RequestTimeTooSkewed"));
assert_eq!(service.message, format!("bar"));
assert_eq!(service.request_id, format!("63145DB90BFD85303279D56B"))
Expand Down

0 comments on commit e74deec

Please sign in to comment.