Skip to content

Commit 895efe9

Browse files
committed
refactor: [#680] http return errors instead of panicking
1 parent 90c7780 commit 895efe9

File tree

3 files changed

+63
-41
lines changed

3 files changed

+63
-41
lines changed

src/console/clients/checker/checks/http.rs

+19-3
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,19 @@ async fn check_http_announce(tracker_url: &Url) -> Result<(), CheckError> {
6161
// We should change the client to catch that error and return a `CheckError`.
6262
// Otherwise the checking process will stop. The idea is to process all checks
6363
// and return a final report.
64-
let response = Client::new(tracker_url.clone())
64+
let Ok(client) = Client::new(tracker_url.clone()) else {
65+
return Err(CheckError::HttpError {
66+
url: (tracker_url.to_owned()),
67+
});
68+
};
69+
let Ok(response) = client
6570
.announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query())
66-
.await;
71+
.await
72+
else {
73+
return Err(CheckError::HttpError {
74+
url: (tracker_url.to_owned()),
75+
});
76+
};
6777

6878
if let Ok(body) = response.bytes().await {
6979
if let Ok(_announce_response) = serde_bencode::from_bytes::<Announce>(&body) {
@@ -89,7 +99,13 @@ async fn check_http_scrape(url: &Url) -> Result<(), CheckError> {
8999
// We should change the client to catch that error and return a `CheckError`.
90100
// Otherwise the checking process will stop. The idea is to process all checks
91101
// and return a final report.
92-
let response = Client::new(url.clone()).scrape(&query).await;
102+
103+
let Ok(client) = Client::new(url.clone()) else {
104+
return Err(CheckError::HttpError { url: (url.to_owned()) });
105+
};
106+
let Ok(response) = client.scrape(&query).await else {
107+
return Err(CheckError::HttpError { url: (url.to_owned()) });
108+
};
93109

94110
if let Ok(body) = response.bytes().await {
95111
if let Ok(_scrape_response) = scrape::Response::try_from_bencoded(&body) {

src/console/clients/http/app.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -64,11 +64,11 @@ async fn announce_command(tracker_url: String, info_hash: String) -> anyhow::Res
6464
let info_hash =
6565
InfoHash::from_str(&info_hash).expect("Invalid infohash. Example infohash: `9c38422213e30bff212b30c360d26f9a02136422`");
6666

67-
let response = Client::new(base_url)
67+
let response = Client::new(base_url)?
6868
.announce(&QueryBuilder::with_default_values().with_info_hash(&info_hash).query())
69-
.await;
69+
.await?;
7070

71-
let body = response.bytes().await.unwrap();
71+
let body = response.bytes().await?;
7272

7373
let announce_response: Announce = serde_bencode::from_bytes(&body)
7474
.unwrap_or_else(|_| panic!("response body should be a valid announce response, got: \"{:#?}\"", &body));
@@ -85,9 +85,9 @@ async fn scrape_command(tracker_url: &str, info_hashes: &[String]) -> anyhow::Re
8585

8686
let query = requests::scrape::Query::try_from(info_hashes).context("failed to parse infohashes")?;
8787

88-
let response = Client::new(base_url).scrape(&query).await;
88+
let response = Client::new(base_url)?.scrape(&query).await?;
8989

90-
let body = response.bytes().await.unwrap();
90+
let body = response.bytes().await?;
9191

9292
let scrape_response = scrape::Response::try_from_bencoded(&body)
9393
.unwrap_or_else(|_| panic!("response body should be a valid scrape response, got: \"{:#?}\"", &body));

src/shared/bit_torrent/tracker/http/client/mod.rs

+39-33
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ pub mod responses;
33

44
use std::net::IpAddr;
55

6+
use anyhow::{anyhow, Result};
67
use requests::announce::{self, Query};
78
use requests::scrape;
89
use reqwest::{Client as ReqwestClient, Response, Url};
@@ -25,78 +26,83 @@ pub struct Client {
2526
/// base url path query
2627
/// ```
2728
impl Client {
28-
/// # Panics
29+
/// # Errors
2930
///
3031
/// This method fails if the client builder fails.
31-
#[must_use]
32-
pub fn new(base_url: Url) -> Self {
33-
Self {
32+
pub fn new(base_url: Url) -> Result<Self> {
33+
let reqwest = reqwest::Client::builder().build()?;
34+
Ok(Self {
3435
base_url,
35-
reqwest: reqwest::Client::builder().build().unwrap(),
36+
reqwest,
3637
key: None,
37-
}
38+
})
3839
}
3940

4041
/// Creates the new client binding it to an specific local address.
4142
///
42-
/// # Panics
43+
/// # Errors
4344
///
4445
/// This method fails if the client builder fails.
45-
#[must_use]
46-
pub fn bind(base_url: Url, local_address: IpAddr) -> Self {
47-
Self {
46+
pub fn bind(base_url: Url, local_address: IpAddr) -> Result<Self> {
47+
let reqwest = reqwest::Client::builder().local_address(local_address).build()?;
48+
Ok(Self {
4849
base_url,
49-
reqwest: reqwest::Client::builder().local_address(local_address).build().unwrap(),
50+
reqwest,
5051
key: None,
51-
}
52+
})
5253
}
5354

54-
/// # Panics
55+
/// # Errors
5556
///
5657
/// This method fails if the client builder fails.
57-
#[must_use]
58-
pub fn authenticated(base_url: Url, key: Key) -> Self {
59-
Self {
58+
pub fn authenticated(base_url: Url, key: Key) -> Result<Self> {
59+
let reqwest = reqwest::Client::builder().build()?;
60+
Ok(Self {
6061
base_url,
61-
reqwest: reqwest::Client::builder().build().unwrap(),
62+
reqwest,
6263
key: Some(key),
63-
}
64+
})
6465
}
6566

66-
pub async fn announce(&self, query: &announce::Query) -> Response {
67+
/// # Errors
68+
pub async fn announce(&self, query: &announce::Query) -> Result<Response> {
6769
self.get(&self.build_announce_path_and_query(query)).await
6870
}
6971

70-
pub async fn scrape(&self, query: &scrape::Query) -> Response {
72+
/// # Errors
73+
pub async fn scrape(&self, query: &scrape::Query) -> Result<Response> {
7174
self.get(&self.build_scrape_path_and_query(query)).await
7275
}
7376

74-
pub async fn announce_with_header(&self, query: &Query, key: &str, value: &str) -> Response {
77+
/// # Errors
78+
pub async fn announce_with_header(&self, query: &Query, key: &str, value: &str) -> Result<Response> {
7579
self.get_with_header(&self.build_announce_path_and_query(query), key, value)
7680
.await
7781
}
7882

79-
pub async fn health_check(&self) -> Response {
83+
/// # Errors
84+
pub async fn health_check(&self) -> Result<Response> {
8085
self.get(&self.build_path("health_check")).await
8186
}
8287

83-
/// # Panics
88+
/// # Errors
8489
///
8590
/// This method fails if there was an error while sending request.
86-
pub async fn get(&self, path: &str) -> Response {
87-
self.reqwest.get(self.build_url(path)).send().await.unwrap()
91+
pub async fn get(&self, path: &str) -> Result<Response> {
92+
match self.reqwest.get(self.build_url(path)).send().await {
93+
Ok(response) => Ok(response),
94+
Err(err) => Err(anyhow!("{err}")),
95+
}
8896
}
8997

90-
/// # Panics
98+
/// # Errors
9199
///
92100
/// This method fails if there was an error while sending request.
93-
pub async fn get_with_header(&self, path: &str, key: &str, value: &str) -> Response {
94-
self.reqwest
95-
.get(self.build_url(path))
96-
.header(key, value)
97-
.send()
98-
.await
99-
.unwrap()
101+
pub async fn get_with_header(&self, path: &str, key: &str, value: &str) -> Result<Response> {
102+
match self.reqwest.get(self.build_url(path)).header(key, value).send().await {
103+
Ok(response) => Ok(response),
104+
Err(err) => Err(anyhow!("{err}")),
105+
}
100106
}
101107

102108
fn build_announce_path_and_query(&self, query: &announce::Query) -> String {

0 commit comments

Comments
 (0)