Beginner Questions - Handling API response Errors & structs #1672
Replies: 2 comments
-
If it could change often, you could use
This might be noticeable by checking the
That's normal. The guides and examples at https://serde.rs/ may be useful.
Looks fine to me. If you're making many requests, it'd be more performant to share the |
Beta Was this translation helpful? Give feedback.
-
@seanmonstar Thank you for the response. It seems there's no way to clone/copy a Reqwest Response so, I'm doing as you suggested, (bringing it first to text). I can then clone that text as needed. I wanted to show you what I did incase you have more suggestions or feedback on what I can do to improve the code (As I'm learning, anything is appreciated). // use anyhow::Result; (this is being used now)
#[tokio::main]
async fn charges(
client: Client,
charge: Charge,
apikey: &str,
) -> Result<ChargesRes, anyhow::Error> {
let client = reqwest::Client::new();
let resp = client
.post("https://api.someapi.io/v0/charges")
.header("Content-Type", "application/json")
.header("apikey", apikey)
.json(&charge)
.send()
.await?;
let status_code = resp.status();
let resp_text = resp.text().await?;
match status_code {
reqwest::StatusCode::OK => dbg!("OK status:"),
s => {
return Err(anyhow::anyhow!(
"Error: status {}, message: {}",
s,
resp_text.clone()
));
}
};
let resp_serialized = serde_json::from_str(&resp_text); // purposely not using the "?" here so I can give a custom error message.
let resp_seralized_2: ChargesRes = match resp_serialized {
Ok(c) => c,
Err(e) => {
return Err(anyhow::anyhow!(
"Was given a good status, but something failed when parsing to json\nserde parse error: {}, \ntext from API: {}\n status code: {}",
e,
resp_text.clone(),
status_code
))
}
};
Ok(resp_seralized_2)
} |
Beta Was this translation helpful? Give feedback.
-
Question 1:
If I get back an unexpected response from an API call, and I can't serialize it into a struct, I'll get a reqwest error like
(From the ChargesRes struct not being satisfied).
But instead I want to see the bad response of a potentially changed API, or a response like "Permission denied" or "API limit reached" or whatever the unexpected message would be.. How can I return this as the error instead of the generic reqwest errors?
Example Code:
Question 2:
Given a sufficiently deep/complicated json response, is it normal to want to perfectly define the response body? Should I just be using a HashMap or something instead?
Question 3:
Is there anything glaring wrong with the way I'm using reqwest and perhaps could benefit from some tips/tricks given this code example?
Beta Was this translation helpful? Give feedback.
All reactions