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

Log type that has failed to deserialize itself from a request #55

Merged
merged 2 commits into from
Dec 12, 2023
Merged
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
25 changes: 5 additions & 20 deletions src/github/api.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::utils::ResponseExt;
use anyhow::{bail, Context};
use hyper_old_types::header::{Link, RelationType};
use log::{debug, trace};
Expand Down Expand Up @@ -138,7 +139,7 @@ impl GitHub {
};
Ok(self
.send(Method::POST, &format!("orgs/{org}/teams"), body)?
.json()?)
.json_annotated()?)
}
}

Expand Down Expand Up @@ -366,7 +367,7 @@ impl GitHub {
} else {
Ok(self
.send(Method::POST, &format!("orgs/{org}/repos"), req)?
.json()?)
.json_annotated()?)
}
}

Expand Down Expand Up @@ -761,7 +762,7 @@ impl GitHub {
) -> Result<Option<T>, anyhow::Error> {
let resp = self.req(method.clone(), url)?.send()?;
match resp.status() {
StatusCode::OK => Ok(Some(resp.json().with_context(|| {
StatusCode::OK => Ok(Some(resp.json_annotated().with_context(|| {
format!("Failed to decode response body on {method} request to '{url}'")
})?)),
StatusCode::NOT_FOUND => Ok(None),
Expand All @@ -785,7 +786,7 @@ impl GitHub {
.send()?
.custom_error_for_status()?;

let res: GraphResult<R> = resp.json().with_context(|| {
let res: GraphResult<R> = resp.json_annotated().with_context(|| {
format!("Failed to decode response body on graphql request with query '{query}'")
})?;
if let Some(error) = res.errors.get(0) {
Expand Down Expand Up @@ -1059,19 +1060,3 @@ pub(crate) enum BranchProtectionOp {
CreateForRepo(String),
UpdateBranchProtection(String),
}

trait ResponseExt {
fn custom_error_for_status(self) -> anyhow::Result<Response>;
}

impl ResponseExt for Response {
fn custom_error_for_status(self) -> anyhow::Result<Response> {
match self.error_for_status_ref() {
Ok(_) => Ok(self),
Err(err) => {
let body = self.text()?;
Err(err).context(format!("Body: {:?}", body))
}
}
}
}
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
mod github;
mod mailgun;
mod team_api;
mod utils;
mod zulip;

use crate::github::SyncGitHub;
Expand Down
5 changes: 4 additions & 1 deletion src/team_api.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::utils::ResponseExt;
use log::{debug, info, trace};
use std::borrow::Cow;
use std::path::PathBuf;
Expand Down Expand Up @@ -47,7 +48,9 @@ impl TeamApi {
.unwrap_or_else(|_| Cow::Borrowed(rust_team_data::v1::BASE_URL));
let url = format!("{base}/{url}");
trace!("http request: GET {}", url);
Ok(reqwest::blocking::get(&url)?.error_for_status()?.json()?)
Ok(reqwest::blocking::get(&url)?
.error_for_status()?
.json_annotated()?)
}
TeamApi::Local(ref path) => {
let dest = tempfile::tempdir()?;
Expand Down
41 changes: 41 additions & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use anyhow::Context;
use reqwest::blocking::Response;
use serde::de::DeserializeOwned;
use std::str::FromStr;

pub trait ResponseExt {
fn custom_error_for_status(self) -> anyhow::Result<Response>;
fn json_annotated<T: DeserializeOwned>(self) -> anyhow::Result<T>;
}

impl ResponseExt for Response {
fn custom_error_for_status(self) -> anyhow::Result<Response> {
match self.error_for_status_ref() {
Ok(_) => Ok(self),
Err(err) => {
let body = self.text()?;
Kobzol marked this conversation as resolved.
Show resolved Hide resolved
Err(err).context(format!("Body: {:?}", body))
Kobzol marked this conversation as resolved.
Show resolved Hide resolved
}
}
}

/// Try to load the response as JSON. If it fails, include the response body
/// as text in the error message, so that it is easier to understand what was
/// the problem.
fn json_annotated<T: DeserializeOwned>(self) -> anyhow::Result<T> {
let text = self.text()?;
Kobzol marked this conversation as resolved.
Show resolved Hide resolved

serde_json::from_str::<T>(&text).with_context(|| {
// Try to at least deserialize as generic JSON, to provide a more readable
// visualization of the response body.
let body_content = serde_json::Value::from_str(&text)
.and_then(|v| serde_json::to_string_pretty(&v))
.unwrap_or(text);

format!(
"Cannot deserialize type `{}` from the following response body:\n{body_content}",
std::any::type_name::<T>(),
)
})
}
}
Loading