Skip to content

Commit

Permalink
Add is_connect on error (seanmonstar#1023)
Browse files Browse the repository at this point in the history
* error: add is_connect helper function

* test: ensure request_timeout is not connect_timeout

* fmt

* skip err is_connect if target_arch is wasm. rerun checks

Co-authored-by: lishuo <lishuo.03@bytedance.com>
Co-authored-by: Sean McArthur <sean@seanmonstar.com>
  • Loading branch information
3 people authored Sep 3, 2020
1 parent f012163 commit e06e198
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
18 changes: 18 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,24 @@ impl Error {
}
}

#[cfg(not(target_arch = "wasm32"))]
/// Returns true if the error is related to connect
pub fn is_connect(&self) -> bool {
let mut source = self.source();

while let Some(err) = source {
if let Some(hyper_err) = err.downcast_ref::<hyper::Error>() {
if hyper_err.is_connect() {
return true;
}
}

source = err.source();
}

false
}

/// Returns true if the error is related to the request or response body
pub fn is_body(&self) -> bool {
match self.inner.kind {
Expand Down
29 changes: 28 additions & 1 deletion tests/timeouts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,37 @@ async fn request_timeout() {

let err = res.unwrap_err();

assert!(err.is_timeout());
if cfg!(not(target_arch = "wasm32")) {
assert!(err.is_timeout() && !err.is_connect());
} else {
assert!(err.is_timeout());
}
assert_eq!(err.url().map(|u| u.as_str()), Some(url.as_str()));
}

#[cfg(not(target_arch = "wasm32"))]
#[tokio::test]
async fn connect_timeout() {
let _ = env_logger::try_init();

let client = reqwest::Client::builder()
.connect_timeout(Duration::from_millis(100))
.build()
.unwrap();

let url = format!("http://10.255.255.1:81/slow");

let res = client
.get(&url)
.timeout(Duration::from_millis(1000))
.send()
.await;

let err = res.unwrap_err();

assert!(err.is_connect() && err.is_timeout());
}

#[tokio::test]
async fn response_timeout() {
let _ = env_logger::try_init();
Expand Down

0 comments on commit e06e198

Please sign in to comment.