Skip to content

Commit

Permalink
Add status code to GithubError (#607)
Browse files Browse the repository at this point in the history
* Add status code to GithubError

* style
  • Loading branch information
flying-sheep authored Mar 19, 2024
1 parent 74f4db5 commit 1cb0d5c
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 7 deletions.
3 changes: 2 additions & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,13 @@ pub enum Error {
}

/// An error returned from GitHub's API.
#[derive(serde::Deserialize, Debug, Clone)]
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct GitHubError {
pub documentation_url: Option<String>,
pub errors: Option<Vec<serde_json::Value>>,
pub message: String,
pub status_code: http::StatusCode,
}

impl fmt::Display for GitHubError {
Expand Down
26 changes: 21 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ use hyper::{Request, Response};

use once_cell::sync::Lazy;
use secrecy::{ExposeSecret, SecretString};
use serde::Serialize;
use serde::{Deserialize, Serialize};
use snafu::*;
use tower::{buffer::Buffer, util::BoxService, BoxError, Layer, Service, ServiceExt};

Expand Down Expand Up @@ -294,6 +294,13 @@ pub fn format_media_type(media_type: impl AsRef<str>) -> String {
format!("application/vnd.github.v3.{media_type}{json_suffix}")
}

#[derive(Debug, Deserialize)]
struct GitHubErrorBody {
pub documentation_url: Option<String>,
pub errors: Option<Vec<serde_json::Value>>,
pub message: String,
}

/// Maps a GitHub error response into and `Err()` variant if the status is
/// not a success.
pub async fn map_github_error(
Expand All @@ -302,12 +309,21 @@ pub async fn map_github_error(
if response.status().is_success() {
Ok(response)
} else {
let b: error::GitHubError =
serde_json::from_slice(response.into_body().collect().await?.to_bytes().as_ref())
.context(error::SerdeSnafu)?;
let (parts, body) = response.into_parts();
let GitHubErrorBody {
documentation_url,
errors,
message,
} = serde_json::from_slice(body.collect().await?.to_bytes().as_ref())
.context(error::SerdeSnafu)?;

Err(error::Error::GitHub {
source: b,
source: GitHubError {
status_code: parts.status,
documentation_url,
errors,
message,
},
backtrace: Backtrace::generate(),
})
}
Expand Down
3 changes: 2 additions & 1 deletion tests/commit_associated_check_runs_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,8 @@ async fn should_fail_when_not_found() {

match result.unwrap_err() {
Error::GitHub { source, .. } => {
assert_eq!("Its gone", source.message)
assert_eq!(http::StatusCode::NOT_FOUND, source.status_code);
assert_eq!("Its gone", source.message);
}
other => panic!("Unexpected error: {:?}", other),
}
Expand Down

0 comments on commit 1cb0d5c

Please sign in to comment.