pub struct ResponseError { /* private fields */ }
Expand description

HTTP 响应错误

Implementations§

创建 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
Hide additional examples
src/client/resolver/simple.rs (line 32)
31
32
33
34
35
36
37
fn convert_io_error_to_response_error(err: IOError, opts: ResolveOptions) -> ResponseError {
    let mut err = ResponseError::new(HttpResponseErrorKind::DnsServerError.into(), err);
    if let Some(retried) = opts.retried() {
        err = err.retried(retried);
    }
    err
}
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/resolver/trust_dns.rs (line 78)
77
78
79
80
81
82
83
fn convert_trust_dns_error_to_response_error(err: ResolveError, opts: ResolveOptions) -> 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)
}

创建 HTTP 响应错误

Examples found in repository?
src/client/call/try_endpoints.rs (line 768)
766
767
768
769
770
771
fn no_try_error(retried: &RetriedStatsInfo) -> TryError {
    TryError::new(
        ResponseError::new_with_msg(ResponseErrorKind::NoTry, "None endpoint is tried").retried(retried),
        RetryDecision::DontRetry.into(),
    )
}
More examples
Hide additional examples
src/client/resolver/chained.rs (line 55)
54
55
56
57
58
59
60
fn no_try_error(opts: ResolveOptions) -> ResponseError {
    let mut err = ResponseError::new_with_msg(ResponseErrorKind::NoTry, "None resolver is tried");
    if let Some(retried) = opts.retried() {
        err = err.retried(retried);
    }
    err
}
src/client/resolver/timeout.rs (lines 116-119)
115
116
117
118
119
120
121
122
123
124
        fn make_timeout_error(timeout: Duration, opts: ResolveOptions) -> ResponseError {
            let mut err = ResponseError::new_with_msg(
                HttpResponseErrorKind::TimeoutError.into(),
                format!("Failed to resolve domain in {timeout:?}"),
            );
            if let Some(retried) = opts.retried() {
                err = err.retried(retried);
            }
            err
        }
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),
            )
        }

设置重试信息

Examples found in repository?
src/client/call/try_endpoints.rs (line 768)
766
767
768
769
770
771
fn no_try_error(retried: &RetriedStatsInfo) -> TryError {
    TryError::new(
        ResponseError::new_with_msg(ResponseErrorKind::NoTry, "None endpoint is tried").retried(retried),
        RetryDecision::DontRetry.into(),
    )
}
More examples
Hide additional examples
src/client/resolver/chained.rs (line 57)
54
55
56
57
58
59
60
fn no_try_error(opts: ResolveOptions) -> ResponseError {
    let mut err = ResponseError::new_with_msg(ResponseErrorKind::NoTry, "None resolver is tried");
    if let Some(retried) = opts.retried() {
        err = err.retried(retried);
    }
    err
}
src/client/resolver/simple.rs (line 34)
31
32
33
34
35
36
37
fn convert_io_error_to_response_error(err: IOError, opts: ResolveOptions) -> ResponseError {
    let mut err = ResponseError::new(HttpResponseErrorKind::DnsServerError.into(), err);
    if let Some(retried) = opts.retried() {
        err = err.retried(retried);
    }
    err
}
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
}
src/client/resolver/trust_dns.rs (line 80)
77
78
79
80
81
82
83
fn convert_trust_dns_error_to_response_error(err: ResolveError, opts: ResolveOptions) -> ResponseError {
    let mut err = ResponseError::new(HttpResponseErrorKind::DnsServerError.into(), err);
    if let Some(retried) = opts.retried() {
        err = err.retried(retried);
    }
    err
}
src/client/resolver/timeout.rs (line 121)
115
116
117
118
119
120
121
122
123
124
        fn make_timeout_error(timeout: Duration, opts: ResolveOptions) -> ResponseError {
            let mut err = ResponseError::new_with_msg(
                HttpResponseErrorKind::TimeoutError.into(),
                format!("Failed to resolve domain in {timeout:?}"),
            );
            if let Some(retried) = opts.retried() {
                err = err.retried(retried);
            }
            err
        }

设置重试决定

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)
}

设置 HTTP 响应信息

Examples found in repository?
src/client/response/error.rs (line 240)
239
240
241
    pub(crate) fn from_endpoint_parse_error(error: EndpointParseError, parts: &HttpResponseParts) -> Self {
        Self::new(ErrorKind::ParseResponseError, error).response_parts(parts)
    }
More examples
Hide additional 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),
            )
        }

直接设置响应体样本

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))
    }

设置响应体样本

该方法的异步版本为 Error::async_read_response_body_sample

Examples found in repository?
src/client/call/utils.rs (line 401)
397
398
399
400
401
402
403
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())?)
    }
}

异步设置响应体样本

Examples found in repository?
src/client/call/utils.rs (line 411)
406
407
408
409
410
411
412
413
414
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?)
    }
}

获取 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
Hide additional 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,
            }
        }
    }

获取重试决定

获取响应体样本

获取服务器 IP 地址

获取服务器端口号

获取 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()
}

获取 HTTP 响应的 X-Log 信息

获取 HTTP 响应的 X-ReqId 信息

获取扩展信息

获取扩展信息的可变引用

Trait Implementations§

Formats the value using the given formatter. Read more
Formats the value using the given formatter. Read more
The lower-level source of this error, if any. Read more
👎Deprecated since 1.42.0: use the Display impl or to_string()
👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type based access to context intended for error reports. Read more
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Converts self into T using Into<T>. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Pipes by value. This is generally the method you want to use. Read more
Borrows self and passes that borrow into the pipe function. Read more
Mutably borrows self and passes that borrow into the pipe function. Read more
Borrows self, then passes self.borrow() into the pipe function. Read more
Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Borrows self, then passes self.as_ref() into the pipe function.
Mutably borrows self, then passes self.as_mut() into the pipe function.
Borrows self, then passes self.deref() into the pipe function.
Mutably borrows self, then passes self.deref_mut() into the pipe function.
🔬This is a nightly-only experimental API. (provide_any)
Data providers should implement this method to provide all values they are able to provide by using demand. Read more
Should always be Self
Immutable access to a value. Read more
Mutable access to a value. Read more
Immutable access to the Borrow<B> of a value. Read more
Mutable access to the BorrowMut<B> of a value. Read more
Immutable access to the AsRef<R> view of a value. Read more
Mutable access to the AsMut<R> view of a value. Read more
Immutable access to the Deref::Target of a value. Read more
Mutable access to the Deref::Target of a value. Read more
Calls .tap() only in debug builds, and is erased in release builds.
Calls .tap_mut() only in debug builds, and is erased in release builds.
Calls .tap_borrow() only in debug builds, and is erased in release builds.
Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
Calls .tap_ref() only in debug builds, and is erased in release builds.
Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
Calls .tap_deref() only in debug builds, and is erased in release builds.
Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
Converts the given value to a String. Read more
Attempts to convert self into T using TryInto<T>. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more