Skip to content

Commit 4677dcd

Browse files
committed
Add custom errors to match other language libraries
1 parent 583ceb8 commit 4677dcd

File tree

4 files changed

+50
-8
lines changed

4 files changed

+50
-8
lines changed

examples/sample/src/main.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,14 @@ async fn main() {
2020
println!("Successfully called \"typeahead\" endpoint.");
2121
if let Ok(body) = response.json().await {
2222
println!("Response Body:");
23-
println!("{:?}", body);
23+
println!("{}", body);
2424
} else {
2525
println!("Response body JSON data parsing error.")
2626
}
2727
}
2828
Err(err) => {
2929
println!("Error calling \"typeahead\" endpoint:");
30-
println!("{:?},", err);
30+
println!("{},", err);
3131
}
3232
};
3333
}

src/client.rs

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
use super::{Api, Result};
1+
use super::{Api, Error, Result};
2+
use http::StatusCode;
23
use reqwest::RequestBuilder;
34
use serde_json::Value;
45
use std::time::Duration;
@@ -143,8 +144,26 @@ impl Client<'_> {
143144
.header("User-Agent", self.user_agent)
144145
.build()?;
145146

147+
let response = self.client.execute(request.try_clone().expect("Error can remain unhandled because we're not using streams, which are the try_clone fail condition")).await;
148+
149+
match &response {
150+
Ok(response) => match response.status() {
151+
StatusCode::NOT_FOUND => return Err(Error::NotFoundError),
152+
StatusCode::UNAUTHORIZED => return Err(Error::AuthenticationError),
153+
StatusCode::TOO_MANY_REQUESTS => return Err(Error::RateLimitError),
154+
StatusCode::BAD_REQUEST => return Err(Error::InvalidRequestError),
155+
StatusCode::INTERNAL_SERVER_ERROR => return Err(Error::ListenApiError),
156+
_ => {}
157+
},
158+
Err(err) => {
159+
if err.is_connect() || err.is_timeout() {
160+
return Err(Error::ApiConnectionError);
161+
}
162+
}
163+
};
164+
146165
Ok(Response {
147-
response: self.client.execute(request.try_clone().expect("Error can remain unhandled because we're not using streams, which are the try_clone fail condition")).await?,
166+
response: response?,
148167
request,
149168
})
150169
}

src/error.rs

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,18 @@
11
/// Error for API calls from [`Client`](super::Client).
22
#[derive(Debug)]
33
pub enum Error {
4+
/// Wrong api key or your account is suspended.
5+
AuthenticationError,
6+
/// Fail to connect to API servers.
7+
ApiConnectionError,
8+
/// Something wrong on your end (client side errors), e.g., missing required parameters.
9+
InvalidRequestError,
10+
/// You are using FREE plan and you exceed the quota limit.
11+
RateLimitError,
12+
/// Endpoint not exist, or podcast / episode not exist.
13+
NotFoundError,
14+
/// Something wrong on our end (unexpected server errors).
15+
ListenApiError,
416
/// Error from http client.
517
Reqwest(reqwest::Error),
618
/// Error from JSON creation/processing.
@@ -24,12 +36,21 @@ impl std::error::Error for Error {
2436
match *self {
2537
Error::Reqwest(ref e) => Some(e),
2638
Error::Json(ref e) => Some(e),
39+
_ => None,
2740
}
2841
}
2942
}
3043

3144
impl std::fmt::Display for Error {
3245
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
33-
write!(f, "{}", *self)
46+
match self {
47+
Error::AuthenticationError => write!(f, "Wrong api key or your account is suspended."),
48+
Error::ApiConnectionError => write!(f, "Fail to connect to API servers."),
49+
Error::InvalidRequestError => write!(f, "Something wrong on your end (client side errors), e.g., missing required parameters."),
50+
Error::RateLimitError => write!(f, "You are using FREE plan and you exceed the quota limit."),
51+
Error::NotFoundError => write!(f, "Endpoint not exist, or podcast / episode not exist."),
52+
Error::ListenApiError => write!(f, "Something wrong on our end (unexpected server errors)."),
53+
Error::Reqwest(_) | Error::Json(_) => write!(f, "{}", self)
54+
}
3455
}
3556
}

tests/client_tests.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,9 +47,11 @@ mod mock {
4747
"q": "dummy",
4848
"sort_by_date": 1
4949
}))
50-
.await
51-
.unwrap();
52-
assert_eq!(response.response.status(), http::StatusCode::UNAUTHORIZED);
50+
.await;
51+
assert!(match response {
52+
Err(podcast_api::Error::AuthenticationError) => true,
53+
_ => false,
54+
});
5355
});
5456
}
5557

0 commit comments

Comments
 (0)