Struct qiniu_http_client::ResponseError
source · pub struct ResponseError { /* private fields */ }
Expand description
HTTP 响应错误
Implementations§
source§impl Error
impl Error
sourcepub fn new(kind: ErrorKind, err: impl Into<AnyError>) -> Self
pub fn new(kind: ErrorKind, err: impl Into<AnyError>) -> Self
创建 HTTP 响应错误
Examples found in repository?
src/client/response/error.rs (line 240)
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
pub(crate) fn from_endpoint_parse_error(error: EndpointParseError, parts: &HttpResponseParts) -> Self {
Self::new(ErrorKind::ParseResponseError, error).response_parts(parts)
}
#[allow(dead_code)]
fn assert() {
assert_impl!(Send: Self);
assert_impl!(Sync: Self);
}
}
#[derive(Debug, Default)]
pub(in super::super) struct XHeaders {
x_log: Option<HeaderValue>,
x_reqid: Option<HeaderValue>,
}
impl From<&HttpResponseParts> for XHeaders {
#[inline]
fn from(parts: &HttpResponseParts) -> Self {
Self {
x_log: extract_x_log_from_response_parts(parts),
x_reqid: extract_x_reqid_from_response_parts(parts),
}
}
}
fn extract_x_log_from_response_parts(parts: &HttpResponseParts) -> Option<HeaderValue> {
parts.header(X_LOG_HEADER_NAME).cloned()
}
fn extract_x_reqid_from_response_parts(parts: &HttpResponseParts) -> Option<HeaderValue> {
parts.header(X_REQ_ID_HEADER_NAME).cloned()
}
fn extract_metrics_from_response_parts(parts: &HttpResponseParts) -> Option<Metrics> {
parts.metrics().cloned()
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{:?}]", self.kind)?;
if let Some(retried) = self.retried.as_ref() {
write!(f, "[{retried}]")?;
}
if let Some(x_reqid) = self.x_headers.x_reqid.as_ref() {
write!(f, "[{x_reqid:?}]")?;
}
if let Some(x_log) = self.x_headers.x_log.as_ref() {
write!(f, "[{x_log:?}]")?;
}
write!(f, " {}", self.error)?;
if !self.response_body_sample.is_empty() {
write!(f, " [{}]", String::from_utf8_lossy(&self.response_body_sample))?;
}
Ok(())
}
}
impl StdError for Error {
#[inline]
fn source(&self) -> Option<&(dyn StdError + 'static)> {
Some(self.error.as_ref())
}
}
impl From<HttpResponseError> for Error {
#[inline]
fn from(error: HttpResponseError) -> Self {
Self::from_http_response_error(error, Default::default(), None)
}
}
impl From<HttpResponseErrorKind> for ErrorKind {
#[inline]
fn from(kind: HttpResponseErrorKind) -> Self {
ErrorKind::HttpError(kind)
}
}
impl From<JsonError> for Error {
#[inline]
fn from(error: JsonError) -> Self {
Self::new(ErrorKind::ParseResponseError, error)
}
}
impl From<IoError> for Error {
#[inline]
fn from(error: IoError) -> Self {
Self::new(ErrorKind::HttpError(HttpResponseErrorKind::LocalIoError), error)
}
}
impl From<ToStringError> for Error {
#[inline]
fn from(error: ToStringError) -> Self {
match error {
ToStringError::CredentialGetError(err) => err.into(),
ToStringError::CallbackError(err) => Self::new(HttpResponseErrorKind::CallbackError.into(), err),
err => Self::new(HttpResponseErrorKind::UnknownError.into(), err),
}
}
More examples
src/client/resolver/c_ares_impl.rs (line 168)
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
fn convert_c_ares_error_to_response_error(err: CAresError, opts: ResolveOptions) -> ResponseError {
let mut err = ResponseError::new(HttpResponseErrorKind::DnsServerError.into(), err);
if let Some(retried) = opts.retried() {
err = err.retried(retried);
}
err
}
fn owned_convert_c_ares_error_to_response_error(err: CAresError, opts: OwnedResolveOptions) -> ResponseError {
let mut err = ResponseError::new(HttpResponseErrorKind::DnsServerError.into(), err);
if let Some(retried) = opts.retried() {
err = err.retried(retried);
}
err
}
src/client/call/utils.rs (line 70)
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
pub(super) fn make_url(
domain_or_ip: &DomainOrIpAddr,
request: &InnerRequestParts<'_>,
retried: &RetriedStatsInfo,
) -> Result<(Uri, Vec<IpAddr>), TryError> {
return _make_url(domain_or_ip, request).map_err(|err| {
TryError::new(
ResponseError::new(HttpResponseErrorKind::InvalidUrl.into(), err).retried(retried),
RetryDecision::TryNextServer.into(),
)
});
fn _make_url(
domain_or_ip: &DomainOrIpAddr,
request: &InnerRequestParts<'_>,
) -> Result<(Uri, Vec<IpAddr>), InvalidUri> {
let mut resolved_ip_addrs = Vec::new();
let scheme = if request.use_https() {
Scheme::HTTPS
} else {
Scheme::HTTP
};
let authority: Authority = match domain_or_ip {
DomainOrIpAddr::Domain {
domain_with_port,
resolved_ips,
} => {
resolved_ip_addrs = resolved_ips.iter().map(|resolved| resolved.ip_addr()).collect();
let mut authority = domain_with_port.domain().to_owned();
if let Some(port) = domain_with_port.port() {
authority.push(':');
authority.push_str(&port.get().to_string());
}
authority.parse()?
}
DomainOrIpAddr::IpAddr(ip_addr_with_port) => ip_addr_with_port.to_string().parse()?,
};
let mut path_and_query = if request.path().starts_with('/') {
request.path().to_owned()
} else {
"/".to_owned() + request.path()
};
if !request.query().is_empty() || !request.query_pairs().is_empty() {
path_and_query.push('?');
let path_len = path_and_query.len();
if !request.query().is_empty() {
path_and_query.push_str(request.query());
}
let mut serializer = form_urlencoded::Serializer::for_suffix(&mut path_and_query, path_len);
serializer.extend_pairs(request.query_pairs().iter());
serializer.finish();
}
let path_and_query: PathAndQuery = path_and_query.parse()?;
let url = Uri::builder()
.scheme(scheme)
.authority(authority)
.path_and_query(path_and_query)
.build()
.unwrap();
Ok((url, resolved_ip_addrs))
}
}
pub(super) fn reset_request_body(body: &mut SyncRequestBody<'_>, retried: &RetriedStatsInfo) -> Result<(), TryError> {
body.reset().map_err(|err| {
TryError::new(
ResponseError::from(err).retried(retried),
RetryDecision::DontRetry.into(),
)
})
}
#[cfg(feature = "async")]
pub(super) async fn reset_async_request_body(
body: &mut AsyncRequestBody<'_>,
retried: &RetriedStatsInfo,
) -> Result<(), TryError> {
body.reset().await.map_err(|err| {
TryError::new(
ResponseError::from(err).retried(retried),
RetryDecision::DontRetry.into(),
)
})
}
pub(super) fn call_before_backoff_callbacks(
request: &InnerRequestParts<'_>,
built: &mut HttpRequestParts<'_>,
retried: &RetriedStatsInfo,
delay: Duration,
) -> Result<(), TryError> {
request
.call_before_backoff_callbacks(&mut ExtendedCallbackContextImpl::new(request, built, retried), delay)
.map_err(|err| make_callback_try_error(err, retried))
}
pub(super) fn call_after_backoff_callbacks(
request: &InnerRequestParts<'_>,
built: &mut HttpRequestParts<'_>,
retried: &RetriedStatsInfo,
delay: Duration,
) -> Result<(), TryError> {
request
.call_after_backoff_callbacks(&mut ExtendedCallbackContextImpl::new(request, built, retried), delay)
.map_err(|err| make_callback_try_error(err, retried))
}
fn call_to_resolve_domain_callbacks(
request: &InnerRequestParts<'_>,
domain: &str,
extensions: &mut Extensions,
retried: &RetriedStatsInfo,
) -> Result<(), TryError> {
let mut context = CallbackContextImpl::new(request, extensions);
request
.call_to_resolve_domain_callbacks(&mut context, domain)
.map_err(|err| make_callback_try_error(err, retried))
}
fn call_domain_resolved_callbacks(
request: &InnerRequestParts<'_>,
domain: &str,
answers: &ResolveAnswers,
extensions: &mut Extensions,
retried: &RetriedStatsInfo,
) -> Result<(), TryError> {
let mut context = CallbackContextImpl::new(request, extensions);
request
.call_domain_resolved_callbacks(&mut context, domain, answers)
.map_err(|err| make_callback_try_error(err, retried))
}
fn call_to_choose_ips_callbacks(
request: &InnerRequestParts<'_>,
ips: &[IpAddrWithPort],
extensions: &mut Extensions,
retried: &RetriedStatsInfo,
) -> Result<(), TryError> {
let mut context = CallbackContextImpl::new(request, extensions);
request
.call_to_choose_ips_callbacks(&mut context, ips)
.map_err(|err| make_callback_try_error(err, retried))
}
fn call_ips_chosen_callbacks(
request: &InnerRequestParts<'_>,
ips: &[IpAddrWithPort],
chosen: &[IpAddrWithPort],
extensions: &mut Extensions,
retried: &RetriedStatsInfo,
) -> Result<(), TryError> {
let mut context = CallbackContextImpl::new(request, extensions);
request
.call_ips_chosen_callbacks(&mut context, ips, chosen)
.map_err(|err| make_callback_try_error(err, retried))
}
pub(super) fn call_before_request_signed_callbacks(
request: &InnerRequestParts<'_>,
built: &mut HttpRequestParts<'_>,
retried: &RetriedStatsInfo,
) -> Result<(), TryError> {
let mut context = ExtendedCallbackContextImpl::new(request, built, retried);
request
.call_before_request_signed_callbacks(&mut context)
.map_err(|err| make_callback_try_error(err, retried))
}
pub(super) fn call_after_request_signed_callbacks(
request: &InnerRequestParts<'_>,
built: &mut HttpRequestParts<'_>,
retried: &RetriedStatsInfo,
) -> Result<(), TryError> {
let mut context = ExtendedCallbackContextImpl::new(request, built, retried);
request
.call_after_request_signed_callbacks(&mut context)
.map_err(|err| make_callback_try_error(err, retried))
}
pub(super) fn call_response_callbacks(
request: &InnerRequestParts<'_>,
built: &mut HttpRequestParts<'_>,
retried: &RetriedStatsInfo,
response: &ResponseParts,
) -> Result<(), ResponseError> {
let mut context = ExtendedCallbackContextImpl::new(request, built, retried);
request
.call_response_callbacks(&mut context, response)
.map_err(|err| make_callback_response_error(err, retried))
}
pub(super) fn call_error_callbacks(
request: &InnerRequestParts<'_>,
built: &mut HttpRequestParts<'_>,
retried: &RetriedStatsInfo,
response_error: &mut ResponseError,
) -> Result<(), TryError> {
let mut context = ExtendedCallbackContextImpl::new(request, built, retried);
request
.call_error_callbacks(&mut context, response_error)
.map_err(|err| make_callback_try_error(err, retried))
}
pub(super) fn find_domains_with_port(endpoints: &[Endpoint]) -> impl Iterator<Item = &DomainWithPort> {
endpoints.iter().filter_map(|endpoint| match endpoint {
Endpoint::DomainWithPort(domain_with_port) => Some(domain_with_port),
_ => None,
})
}
pub(super) fn find_ip_addr_with_port(endpoints: &[Endpoint]) -> impl Iterator<Item = &IpAddrWithPort> {
endpoints.iter().filter_map(|endpoint| match endpoint {
Endpoint::IpAddrWithPort(ip_addr_with_port) => Some(ip_addr_with_port),
_ => None,
})
}
pub(super) fn sign_request(
request: &mut SyncHttpRequest<'_>,
authorization: Option<&Authorization<'_>>,
retried: &RetriedStatsInfo,
) -> Result<(), TryError> {
if let Some(authorization) = authorization {
authorization
.sign(request)
.map_err(|err| handle_sign_request_error(err, retried))?;
}
Ok(())
}
fn handle_sign_request_error(err: AuthorizationError, retried: &RetriedStatsInfo) -> TryError {
match err {
AuthorizationError::IoError(err) => make_local_io_try_error(err, retried),
AuthorizationError::UrlParseError(err) => make_parse_try_error(err, retried),
AuthorizationError::CallbackError(err) => make_callback_try_error(err, retried),
}
}
fn make_local_io_try_error(err: IoError, retried: &RetriedStatsInfo) -> TryError {
TryError::new(
ResponseError::new(ResponseErrorKind::HttpError(HttpResponseErrorKind::LocalIoError), err).retried(retried),
RetryDecision::DontRetry.into(),
)
}
fn make_parse_try_error(err: UrlParseError, retried: &RetriedStatsInfo) -> TryError {
TryError::new(
ResponseError::new(ResponseErrorKind::HttpError(HttpResponseErrorKind::InvalidUrl), err).retried(retried),
RetryDecision::TryNextServer.into(),
)
}
fn make_callback_try_error(err: AnyError, retried: &RetriedStatsInfo) -> TryError {
TryError::new(
make_callback_response_error(err, retried),
RetryDecision::DontRetry.into(),
)
}
fn make_callback_response_error(err: AnyError, retried: &RetriedStatsInfo) -> ResponseError {
ResponseError::new(HttpResponseErrorKind::CallbackError.into(), err).retried(retried)
}
sourcepub fn new_with_msg(
kind: ErrorKind,
msg: impl Display + Debug + Send + Sync + 'static
) -> Self
pub fn new_with_msg(
kind: ErrorKind,
msg: impl Display + Debug + Send + Sync + 'static
) -> Self
创建 HTTP 响应错误
Examples found in repository?
More examples
src/client/call/utils.rs (line 390)
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
fn to_status_code_error(response: SyncResponse, retried: &RetriedStatsInfo) -> ApiResult<SyncResponse> {
let status_code = response.status_code();
let (parts, body) = response.parse_json::<ErrorResponseBody>()?.into_parts_and_body();
Err(
ResponseError::new_with_msg(ResponseErrorKind::StatusCodeError(status_code), body.into_error())
.response_parts(&parts)
.retried(retried),
)
}
}
fn check_x_req_id(response: &mut SyncResponse, retried: &RetriedStatsInfo) -> ApiResult<()> {
if response.x_reqid().is_some() {
Ok(())
} else {
Err(make_malicious_response(response.parts(), retried).read_response_body_sample(response.body_mut())?)
}
}
#[cfg(feature = "async")]
async fn async_check_x_req_id(response: &mut AsyncResponse, retried: &RetriedStatsInfo) -> ApiResult<()> {
if response.x_reqid().is_some() {
Ok(())
} else {
Err(make_malicious_response(response.parts(), retried)
.async_read_response_body_sample(response.body_mut())
.await?)
}
}
fn make_malicious_response(parts: &ResponseParts, retried: &RetriedStatsInfo) -> ResponseError {
ResponseError::new_with_msg(
ResponseErrorKind::MaliciousResponse,
"cannot find X-ReqId header from response, might be malicious response",
)
.response_parts(parts)
.retried(retried)
}
fn make_unexpected_status_code_error(parts: &ResponseParts, retried: &RetriedStatsInfo) -> ResponseError {
ResponseError::new_with_msg(
ResponseErrorKind::UnexpectedStatusCode(parts.status_code()),
format!("status code {} is unexpected", parts.status_code()),
)
.response_parts(parts)
.retried(retried)
}
#[cfg(feature = "async")]
mod async_utils {
use super::{
super::super::{AsyncResponse, InnerRequestParts},
*,
};
use qiniu_http::AsyncRequest as AsyncHttpRequest;
use std::future::Future;
pub(in super::super) async fn sign_async_request(
request: &mut AsyncHttpRequest<'_>,
authorization: Option<&Authorization<'_>>,
retried: &RetriedStatsInfo,
) -> Result<(), TryError> {
if let Some(authorization) = authorization {
authorization
.async_sign(request)
.await
.map_err(|err| handle_sign_request_error(err, retried))?;
}
Ok(())
}
pub(in super::super) async fn async_resolve(
parts: &InnerRequestParts<'_>,
domain_with_port: &DomainWithPort,
extensions: &mut Extensions,
retried: &RetriedStatsInfo,
) -> Result<Vec<IpAddrWithPort>, TryError> {
let answers = with_resolve_domain(parts, domain_with_port.domain(), extensions, retried, || async {
parts
.http_client()
.resolver()
.async_resolve(
domain_with_port.domain(),
ResolveOptions::builder().retried(retried).build(),
)
.await
});
return Ok(answers
.await?
.into_ip_addrs()
.iter()
.map(|&ip| IpAddrWithPort::new(ip, domain_with_port.port()))
.collect());
async fn with_resolve_domain<F: FnOnce() -> Fu, Fu: Future<Output = ResolveResult>>(
parts: &InnerRequestParts<'_>,
domain: &str,
extensions: &mut Extensions,
retried: &RetriedStatsInfo,
f: F,
) -> Result<ResolveAnswers, TryError> {
call_to_resolve_domain_callbacks(parts, domain, extensions, retried)?;
let answers = f()
.await
.map_err(|err| TryError::new(err, RetryDecision::TryNextServer.into()))?;
call_domain_resolved_callbacks(parts, domain, &answers, extensions, retried)?;
Ok(answers)
}
}
pub(in super::super) async fn async_choose(
parts: &InnerRequestParts<'_>,
ips: &[IpAddrWithPort],
extensions: &mut Extensions,
retried: &RetriedStatsInfo,
) -> Result<Vec<IpAddrWithPort>, TryError> {
call_to_choose_ips_callbacks(parts, ips, extensions, retried)?;
let chosen_ips = parts
.http_client()
.chooser()
.async_choose(ips, Default::default())
.await
.into_ip_addrs();
call_ips_chosen_callbacks(parts, ips, &chosen_ips, extensions, retried)?;
Ok(chosen_ips)
}
pub(in super::super) async fn async_judge(
mut response: AsyncResponse,
retried: &RetriedStatsInfo,
) -> ApiResult<AsyncResponse> {
return match response.status_code().as_u16() {
0..=199 | 300..=399 => Err(make_unexpected_status_code_error(response.parts(), retried)),
200..=299 => {
async_check_x_req_id(&mut response, retried).await?;
Ok(response)
}
_ => to_status_code_error(response, retried).await,
};
async fn to_status_code_error(response: AsyncResponse, retried: &RetriedStatsInfo) -> ApiResult<AsyncResponse> {
let status_code = response.status_code();
let (parts, body) = response.parse_json::<ErrorResponseBody>().await?.into_parts_and_body();
Err(
ResponseError::new_with_msg(ResponseErrorKind::StatusCodeError(status_code), body.into_error())
.response_parts(&parts)
.retried(retried),
)
}
sourcepub fn retried(self, retried: &RetriedStatsInfo) -> Self
pub fn retried(self, retried: &RetriedStatsInfo) -> Self
设置重试信息
Examples found in repository?
More examples
src/client/resolver/c_ares_impl.rs (line 170)
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
fn convert_c_ares_error_to_response_error(err: CAresError, opts: ResolveOptions) -> ResponseError {
let mut err = ResponseError::new(HttpResponseErrorKind::DnsServerError.into(), err);
if let Some(retried) = opts.retried() {
err = err.retried(retried);
}
err
}
fn owned_convert_c_ares_error_to_response_error(err: CAresError, opts: OwnedResolveOptions) -> ResponseError {
let mut err = ResponseError::new(HttpResponseErrorKind::DnsServerError.into(), err);
if let Some(retried) = opts.retried() {
err = err.retried(retried);
}
err
}
Additional examples can be found in:
sourcepub fn set_retry_decision(self, retry_decision: RetryDecision) -> Self
pub fn set_retry_decision(self, retry_decision: RetryDecision) -> Self
设置重试决定
Examples found in repository?
src/client/call/send_http_request.rs (line 101)
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
fn handle_response_error(
mut response_error: ResponseError,
http_parts: &mut HttpRequestParts,
parts: &InnerRequestParts<'_>,
retried: &mut RetriedStatsInfo,
) -> TryError {
let retry_result = parts.http_client().request_retrier().retry(
http_parts,
RequestRetrierOptions::builder(&response_error, retried)
.idempotent(parts.idempotent())
.build(),
);
retried.increase_current_endpoint();
response_error = response_error.set_retry_decision(retry_result.decision());
TryError::new(response_error, retry_result)
}
sourcepub fn response_parts(self, response_parts: &HttpResponseParts) -> Self
pub fn response_parts(self, response_parts: &HttpResponseParts) -> Self
设置 HTTP 响应信息
Examples found in repository?
More examples
src/client/call/utils.rs (line 391)
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
fn to_status_code_error(response: SyncResponse, retried: &RetriedStatsInfo) -> ApiResult<SyncResponse> {
let status_code = response.status_code();
let (parts, body) = response.parse_json::<ErrorResponseBody>()?.into_parts_and_body();
Err(
ResponseError::new_with_msg(ResponseErrorKind::StatusCodeError(status_code), body.into_error())
.response_parts(&parts)
.retried(retried),
)
}
}
fn check_x_req_id(response: &mut SyncResponse, retried: &RetriedStatsInfo) -> ApiResult<()> {
if response.x_reqid().is_some() {
Ok(())
} else {
Err(make_malicious_response(response.parts(), retried).read_response_body_sample(response.body_mut())?)
}
}
#[cfg(feature = "async")]
async fn async_check_x_req_id(response: &mut AsyncResponse, retried: &RetriedStatsInfo) -> ApiResult<()> {
if response.x_reqid().is_some() {
Ok(())
} else {
Err(make_malicious_response(response.parts(), retried)
.async_read_response_body_sample(response.body_mut())
.await?)
}
}
fn make_malicious_response(parts: &ResponseParts, retried: &RetriedStatsInfo) -> ResponseError {
ResponseError::new_with_msg(
ResponseErrorKind::MaliciousResponse,
"cannot find X-ReqId header from response, might be malicious response",
)
.response_parts(parts)
.retried(retried)
}
fn make_unexpected_status_code_error(parts: &ResponseParts, retried: &RetriedStatsInfo) -> ResponseError {
ResponseError::new_with_msg(
ResponseErrorKind::UnexpectedStatusCode(parts.status_code()),
format!("status code {} is unexpected", parts.status_code()),
)
.response_parts(parts)
.retried(retried)
}
#[cfg(feature = "async")]
mod async_utils {
use super::{
super::super::{AsyncResponse, InnerRequestParts},
*,
};
use qiniu_http::AsyncRequest as AsyncHttpRequest;
use std::future::Future;
pub(in super::super) async fn sign_async_request(
request: &mut AsyncHttpRequest<'_>,
authorization: Option<&Authorization<'_>>,
retried: &RetriedStatsInfo,
) -> Result<(), TryError> {
if let Some(authorization) = authorization {
authorization
.async_sign(request)
.await
.map_err(|err| handle_sign_request_error(err, retried))?;
}
Ok(())
}
pub(in super::super) async fn async_resolve(
parts: &InnerRequestParts<'_>,
domain_with_port: &DomainWithPort,
extensions: &mut Extensions,
retried: &RetriedStatsInfo,
) -> Result<Vec<IpAddrWithPort>, TryError> {
let answers = with_resolve_domain(parts, domain_with_port.domain(), extensions, retried, || async {
parts
.http_client()
.resolver()
.async_resolve(
domain_with_port.domain(),
ResolveOptions::builder().retried(retried).build(),
)
.await
});
return Ok(answers
.await?
.into_ip_addrs()
.iter()
.map(|&ip| IpAddrWithPort::new(ip, domain_with_port.port()))
.collect());
async fn with_resolve_domain<F: FnOnce() -> Fu, Fu: Future<Output = ResolveResult>>(
parts: &InnerRequestParts<'_>,
domain: &str,
extensions: &mut Extensions,
retried: &RetriedStatsInfo,
f: F,
) -> Result<ResolveAnswers, TryError> {
call_to_resolve_domain_callbacks(parts, domain, extensions, retried)?;
let answers = f()
.await
.map_err(|err| TryError::new(err, RetryDecision::TryNextServer.into()))?;
call_domain_resolved_callbacks(parts, domain, &answers, extensions, retried)?;
Ok(answers)
}
}
pub(in super::super) async fn async_choose(
parts: &InnerRequestParts<'_>,
ips: &[IpAddrWithPort],
extensions: &mut Extensions,
retried: &RetriedStatsInfo,
) -> Result<Vec<IpAddrWithPort>, TryError> {
call_to_choose_ips_callbacks(parts, ips, extensions, retried)?;
let chosen_ips = parts
.http_client()
.chooser()
.async_choose(ips, Default::default())
.await
.into_ip_addrs();
call_ips_chosen_callbacks(parts, ips, &chosen_ips, extensions, retried)?;
Ok(chosen_ips)
}
pub(in super::super) async fn async_judge(
mut response: AsyncResponse,
retried: &RetriedStatsInfo,
) -> ApiResult<AsyncResponse> {
return match response.status_code().as_u16() {
0..=199 | 300..=399 => Err(make_unexpected_status_code_error(response.parts(), retried)),
200..=299 => {
async_check_x_req_id(&mut response, retried).await?;
Ok(response)
}
_ => to_status_code_error(response, retried).await,
};
async fn to_status_code_error(response: AsyncResponse, retried: &RetriedStatsInfo) -> ApiResult<AsyncResponse> {
let status_code = response.status_code();
let (parts, body) = response.parse_json::<ErrorResponseBody>().await?.into_parts_and_body();
Err(
ResponseError::new_with_msg(ResponseErrorKind::StatusCodeError(status_code), body.into_error())
.response_parts(&parts)
.retried(retried),
)
}
sourcepub fn set_response_body_sample(self, body: Vec<u8>) -> Self
pub fn set_response_body_sample(self, body: Vec<u8>) -> Self
直接设置响应体样本
Examples found in repository?
src/client/response/mod.rs (line 120)
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
pub fn parse_json<T: DeserializeOwned>(self) -> ApiResult<Response<T>> {
let x_headers = XHeaders::from(self.parts());
let mut got_body = Vec::new();
let json_response = self
.fulfill()?
.try_map_body(|mut body| parse_json_from_slice(&body).tap_err(|_| got_body = take(&mut body)))
.map_err(|err| {
ResponseError::from_http_response_error(
err.into_response_error(HttpResponseErrorKind::ReceiveError),
x_headers,
Some(ResponseErrorKind::ParseResponseError),
)
.set_response_body_sample(got_body)
})?;
Ok(Response::from(json_response))
}
pub(super) fn fulfill(self) -> ApiResult<HttpResponse<Vec<u8>>> {
let x_headers = XHeaders::from(self.parts());
self.0
.try_map_body(|mut body| {
let mut buf = Vec::new();
io_copy(&mut body, &mut buf).map(|_| buf)
})
.map_err(|err| {
ResponseError::from_http_response_error(
err.into_response_error(HttpResponseErrorKind::ReceiveError),
x_headers,
None,
)
})
}
}
#[cfg(feature = "async")]
impl Response<AsyncResponseBody> {
/// 异步解析 JSON 响应体
pub async fn parse_json<T: DeserializeOwned>(self) -> ApiResult<Response<T>> {
let x_headers = XHeaders::from(self.parts());
let mut got_body = Vec::new();
let json_response = self
.fulfill()
.await?
.try_map_body(|mut body| parse_json_from_slice(&body).tap_err(|_| got_body = take(&mut body)))
.map_err(|err| {
ResponseError::from_http_response_error(
err.into_response_error(HttpResponseErrorKind::ReceiveError),
x_headers,
Some(ResponseErrorKind::ParseResponseError),
)
.set_response_body_sample(got_body)
})?;
Ok(Response::from(json_response))
}
sourcepub fn read_response_body_sample<R: Read>(self, body: R) -> IOResult<Self>
pub fn read_response_body_sample<R: Read>(self, body: R) -> IOResult<Self>
设置响应体样本
该方法的异步版本为 Error::async_read_response_body_sample
。
sourcepub async fn async_read_response_body_sample<R: AsyncRead + Unpin>(
self,
body: R
) -> IOResult<Self>
pub async fn async_read_response_body_sample<R: AsyncRead + Unpin>(
self,
body: R
) -> IOResult<Self>
异步设置响应体样本
sourcepub fn kind(&self) -> ErrorKind
pub fn kind(&self) -> ErrorKind
获取 HTTP 响应错误类型
Examples found in repository?
src/client/call/error.rs (line 29)
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
pub(super) fn feedback_response_error(&self) -> Option<&ResponseError> {
match &self.response_error.kind() {
ResponseErrorKind::HttpError(error_kind) => match error_kind {
HttpResponseErrorKind::ConnectError
| HttpResponseErrorKind::ProxyError
| HttpResponseErrorKind::DnsServerError
| HttpResponseErrorKind::UnknownHostError
| HttpResponseErrorKind::SendError
| HttpResponseErrorKind::ReceiveError
| HttpResponseErrorKind::CallbackError => Some(self.response_error()),
_ => None,
},
ResponseErrorKind::StatusCodeError(status_code) => match status_code.as_u16() {
500..=599 => Some(self.response_error()),
_ => None,
},
ResponseErrorKind::ParseResponseError
| ResponseErrorKind::UnexpectedEof
| ResponseErrorKind::MaliciousResponse => Some(self.response_error()),
ResponseErrorKind::UnexpectedStatusCode(_)
| ResponseErrorKind::SystemCallError
| ResponseErrorKind::NoTry => None,
}
}
More examples
src/client/retrier/error.rs (line 13)
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
fn retry(&self, request: &mut HttpRequestParts, opts: RequestRetrierOptions) -> RetryResult {
return match opts.response_error().kind() {
ResponseErrorKind::HttpError(http_err_kind) => match http_err_kind {
HttpResponseErrorKind::ProtocolError => RetryDecision::RetryRequest,
HttpResponseErrorKind::InvalidUrl => RetryDecision::TryNextServer,
HttpResponseErrorKind::ConnectError => RetryDecision::TryNextServer,
HttpResponseErrorKind::ProxyError => RetryDecision::RetryRequest,
HttpResponseErrorKind::DnsServerError => RetryDecision::RetryRequest,
HttpResponseErrorKind::UnknownHostError => RetryDecision::TryNextServer,
HttpResponseErrorKind::SendError => RetryDecision::RetryRequest,
HttpResponseErrorKind::ReceiveError | HttpResponseErrorKind::UnknownError => {
if is_idempotent(request, opts.idempotent()) {
RetryDecision::RetryRequest
} else {
RetryDecision::DontRetry
}
}
HttpResponseErrorKind::LocalIoError => RetryDecision::DontRetry,
HttpResponseErrorKind::TimeoutError => RetryDecision::RetryRequest,
HttpResponseErrorKind::ServerCertError => RetryDecision::TryAlternativeEndpoints,
HttpResponseErrorKind::ClientCertError => RetryDecision::DontRetry,
HttpResponseErrorKind::TooManyRedirect => RetryDecision::DontRetry,
HttpResponseErrorKind::CallbackError => RetryDecision::DontRetry,
_ => RetryDecision::RetryRequest,
},
ResponseErrorKind::UnexpectedStatusCode(_) => RetryDecision::DontRetry,
ResponseErrorKind::StatusCodeError(status_code) => match status_code.as_u16() {
0..=399 => panic!("Should not arrive here"),
400..=499 | 501 | 579 | 608 | 612 | 614 | 616 | 618 | 630 | 631 | 632 | 640 | 701 => {
RetryDecision::DontRetry
}
509 | 573 => RetryDecision::Throttled,
_ => RetryDecision::TryNextServer,
},
ResponseErrorKind::ParseResponseError | ResponseErrorKind::UnexpectedEof => {
if is_idempotent(request, opts.idempotent()) {
RetryDecision::RetryRequest
} else {
RetryDecision::DontRetry
}
}
ResponseErrorKind::MaliciousResponse => RetryDecision::RetryRequest,
ResponseErrorKind::NoTry | ResponseErrorKind::SystemCallError => RetryDecision::DontRetry,
}
.into();
fn is_idempotent(request: &HttpRequestParts, idempotent: Idempotent) -> bool {
match idempotent {
Idempotent::Always => true,
Idempotent::Default => request.method().is_safe(),
Idempotent::Never => false,
}
}
}
sourcepub fn retry_decision(&self) -> Option<RetryDecision>
pub fn retry_decision(&self) -> Option<RetryDecision>
获取重试决定
sourcepub fn response_body_sample(&self) -> &[u8] ⓘ
pub fn response_body_sample(&self) -> &[u8] ⓘ
获取响应体样本
sourcepub fn server_port(&self) -> Option<NonZeroU16>
pub fn server_port(&self) -> Option<NonZeroU16>
获取服务器端口号
sourcepub fn metrics(&self) -> Option<&Metrics>
pub fn metrics(&self) -> Option<&Metrics>
获取 HTTP 响应指标信息
Examples found in repository?
src/client/call/try_domain_or_ip_addr.rs (line 115)
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
fn make_negative_feedback<'f>(
ips: &'f [IpAddrWithPort],
domain: Option<&'f DomainWithPort>,
parts: &'f mut HttpRequestParts,
err: &'f TryError,
retried: &'f RetriedStatsInfo,
) -> ChooserFeedback<'f> {
let mut builder = ChooserFeedback::builder(ips);
builder.retried(retried).extensions(parts.extensions_mut());
if let Some(domain) = domain {
builder.domain(domain);
}
if let Some(metrics) = err.response_error().metrics() {
builder.metrics(metrics);
}
if let Some(error) = err.feedback_response_error() {
builder.error(error);
}
builder.build()
}
sourcepub fn x_log(&self) -> Option<&HeaderValue>
pub fn x_log(&self) -> Option<&HeaderValue>
获取 HTTP 响应的 X-Log 信息
sourcepub fn x_reqid(&self) -> Option<&HeaderValue>
pub fn x_reqid(&self) -> Option<&HeaderValue>
获取 HTTP 响应的 X-ReqId 信息
sourcepub fn extensions(&self) -> &Extensions
pub fn extensions(&self) -> &Extensions
获取扩展信息
sourcepub fn extensions_mut(&mut self) -> &mut Extensions
pub fn extensions_mut(&mut self) -> &mut Extensions
获取扩展信息的可变引用
Trait Implementations§
source§impl Error for Error
impl Error for Error
source§fn source(&self) -> Option<&(dyn StdError + 'static)>
fn source(&self) -> Option<&(dyn StdError + 'static)>
The lower-level source of this error, if any. Read more
1.0.0 · source§fn description(&self) -> &str
fn description(&self) -> &str
👎Deprecated since 1.42.0: use the Display impl or to_string()
source§impl From<Error> for Error
impl From<Error> for Error
source§fn from(error: HttpResponseError) -> Self
fn from(error: HttpResponseError) -> Self
Converts to this type from the input type.
source§impl From<ToStringError> for Error
impl From<ToStringError> for Error
source§fn from(error: ToStringError) -> Self
fn from(error: ToStringError) -> Self
Converts to this type from the input type.
Auto Trait Implementations§
impl !RefUnwindSafe for Error
impl Send for Error
impl Sync for Error
impl Unpin for Error
impl !UnwindSafe for Error
Blanket Implementations§
source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
source§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
source§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
Pipes by value. This is generally the method you want to use. Read more
source§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
Borrows
self
and passes that borrow into the pipe function. Read moresource§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
Mutably borrows
self
and passes that borrow into the pipe function. Read moresource§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> Rwhere
Self: Borrow<B>,
B: 'a + ?Sized,
R: 'a,
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> Rwhere
Self: Borrow<B>,
B: 'a + ?Sized,
R: 'a,
source§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R
) -> Rwhere
Self: BorrowMut<B>,
B: 'a + ?Sized,
R: 'a,
fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R
) -> Rwhere
Self: BorrowMut<B>,
B: 'a + ?Sized,
R: 'a,
source§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> Rwhere
Self: AsRef<U>,
U: 'a + ?Sized,
R: 'a,
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> Rwhere
Self: AsRef<U>,
U: 'a + ?Sized,
R: 'a,
Borrows
self
, then passes self.as_ref()
into the pipe function.source§fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> Rwhere
Self: AsMut<U>,
U: 'a + ?Sized,
R: 'a,
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> Rwhere
Self: AsMut<U>,
U: 'a + ?Sized,
R: 'a,
Mutably borrows
self
, then passes self.as_mut()
into the pipe
function.source§impl<T> Tap for T
impl<T> Tap for T
source§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Selfwhere
Self: Borrow<B>,
B: ?Sized,
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Selfwhere
Self: Borrow<B>,
B: ?Sized,
Immutable access to the
Borrow<B>
of a value. Read moresource§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere
Self: BorrowMut<B>,
B: ?Sized,
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere
Self: BorrowMut<B>,
B: ?Sized,
Mutable access to the
BorrowMut<B>
of a value. Read moresource§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Selfwhere
Self: AsRef<R>,
R: ?Sized,
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Selfwhere
Self: AsRef<R>,
R: ?Sized,
Immutable access to the
AsRef<R>
view of a value. Read moresource§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere
Self: AsMut<R>,
R: ?Sized,
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere
Self: AsMut<R>,
R: ?Sized,
Mutable access to the
AsMut<R>
view of a value. Read moresource§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Selfwhere
Self: Deref<Target = T>,
T: ?Sized,
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Selfwhere
Self: Deref<Target = T>,
T: ?Sized,
Immutable access to the
Deref::Target
of a value. Read moresource§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Selfwhere
Self: DerefMut<Target = T> + Deref,
T: ?Sized,
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Selfwhere
Self: DerefMut<Target = T> + Deref,
T: ?Sized,
Mutable access to the
Deref::Target
of a value. Read moresource§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
Calls
.tap()
only in debug builds, and is erased in release builds.source§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
Calls
.tap_mut()
only in debug builds, and is erased in release
builds.source§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Selfwhere
Self: Borrow<B>,
B: ?Sized,
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Selfwhere
Self: Borrow<B>,
B: ?Sized,
Calls
.tap_borrow()
only in debug builds, and is erased in release
builds.source§fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere
Self: BorrowMut<B>,
B: ?Sized,
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere
Self: BorrowMut<B>,
B: ?Sized,
Calls
.tap_borrow_mut()
only in debug builds, and is erased in release
builds.source§fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Selfwhere
Self: AsRef<R>,
R: ?Sized,
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Selfwhere
Self: AsRef<R>,
R: ?Sized,
Calls
.tap_ref()
only in debug builds, and is erased in release
builds.source§fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere
Self: AsMut<R>,
R: ?Sized,
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere
Self: AsMut<R>,
R: ?Sized,
Calls
.tap_ref_mut()
only in debug builds, and is erased in release
builds.