Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(ensure_status): display request body in most error cases #29

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ http = "0.2"
reqwest = { version = "0.11", features = ["json"] }
restest_macros = "0.1.0"
serde = "1.0"
serde_json = "1.0"
anyhow = "1.0.58"

[dev-dependencies]
Expand Down
40 changes: 24 additions & 16 deletions src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,33 +299,41 @@ impl RequestResult {
/// Checks if the response status meets an expected status code and convert
/// the body to a concrete type.
///
/// This method uses `serde` internally, so the output type must implement
/// This method uses `serde_json`, so the output type must implement
/// [`DeserializeOwned`].
///
/// # Error
///
/// This method return an error if the server response status is not equal to
/// `status` or if the body can not be deserialized to the specified type.
/// `status` or if the body can not be deserialized to the specified type or if the body is incorrectly formatted.
#[track_caller]
pub async fn ensure_status<T>(self, status: StatusCode) -> Result<T, String>
where
T: DeserializeOwned,
{
if self.response.status() != status {
return Err(format!("Unexpected server response code for request '{}'. Body is {}",
self.context_description,
self.response.text().await.map_err(
|err| {
format!("Unexpected server response code for request {} : {}. Unable to read response body",self.context_description, err)
}
)?));
}
let response_status = self.response.status();
let response_text = self.response.text().await;

self.response.json().await.map_err(|err| {
format!(
"Failed to deserialize body for request '{}': {}",
match response_text {
Err(err) => Err(format!(
"Incorrectly formatted body for request '{}': {}",
self.context_description, err
)
})
)),
Ok(text) => {
if response_status != status {
Err(format!(
"Unexpected server response code for request '{}'. Body is {}",
self.context_description, text
))
} else {
serde_json::from_str(&text).map_err(|err| {
format!(
"Failed to deserialize body for request '{}': {}. Body is {}",
self.context_description, err, text
)
})
}
}
}
}
}