-
-
Notifications
You must be signed in to change notification settings - Fork 5
ref(server): Capture errors from backend servers in Sentry #525
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
Draft
jan-auer
wants to merge
1
commit into
main
Choose a base branch
from
ref/backend-response-errors
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+218
−60
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| //! HTTP response status checking with error body parsing. | ||
| //! | ||
| //! Provides [`ResponseExt`], an extension trait that replaces | ||
| //! [`reqwest::Response::error_for_status`] with a version that reads the | ||
| //! response body on 4xx/5xx errors and parses the structured error code and | ||
| //! message from it (JSON for GCS JSON API, XML for GCS XML API and S3). | ||
|
|
||
| use reqwest::{Response, header}; | ||
| use serde::Deserialize; | ||
|
|
||
| use crate::error::{Error, Result}; | ||
|
|
||
| const MAX_ERROR_BODY_LEN: usize = 1024; | ||
|
|
||
| /// GCS JSON API error envelope (`{"error": {"message": "...", ...}}`). | ||
| #[derive(Deserialize)] | ||
| struct JsonApiError { | ||
| error: JsonApiErrorDetail, | ||
| } | ||
|
|
||
| /// Inner detail of a GCS JSON API error response. | ||
| #[derive(Deserialize)] | ||
| struct JsonApiErrorDetail { | ||
| #[serde(default)] | ||
| message: String, | ||
| #[serde(default)] | ||
| errors: Vec<JsonApiErrorEntry>, | ||
| } | ||
|
|
||
| /// Individual error entry in the GCS JSON API `errors` array. | ||
| #[derive(Deserialize)] | ||
| struct JsonApiErrorEntry { | ||
| #[serde(default)] | ||
| reason: String, | ||
| } | ||
|
|
||
| /// GCS XML API / S3 error body (`<Error><Code>...</Code><Message>...</Message></Error>`). | ||
| #[derive(Deserialize)] | ||
| #[serde(rename_all = "PascalCase")] | ||
| struct XmlApiError { | ||
| #[serde(default)] | ||
| code: String, | ||
| #[serde(default)] | ||
| message: String, | ||
| } | ||
|
|
||
| /// Extension trait for [`reqwest::Response`] that preserves error response bodies. | ||
| /// | ||
| /// Use `check_status` instead of [`reqwest::Response::error_for_status`] to avoid | ||
| /// losing the response body on 4xx/5xx errors. The method parses the structured | ||
| /// error body (JSON or XML) and returns an [`Error::BackendResponse`] with the | ||
| /// extracted error code and message. | ||
| /// | ||
| /// Implemented for both [`reqwest::Response`] and `Result<Response, reqwest::Error>` | ||
| /// so it can be chained directly after `.send().await`. | ||
| pub trait ResponseExt { | ||
| /// Checks the HTTP status and returns the response on success. | ||
| /// | ||
| /// On 4xx/5xx status codes, reads the response body and parses the error code | ||
| /// and message from it (JSON for GCS JSON API, XML for GCS XML API and S3). | ||
| /// For other error statuses (e.g., redirects), falls back to | ||
| /// [`reqwest::Response::error_for_status`]. | ||
| /// | ||
| /// When called on `Result<Response, reqwest::Error>`, transport errors are | ||
| /// wrapped as [`Error::Reqwest`] with the same context string. | ||
| async fn check_error(self, context: &'static str) -> Result<Response>; | ||
| } | ||
|
|
||
| impl ResponseExt for Response { | ||
| async fn check_error(self, context: &'static str) -> Result<Response> { | ||
| let status = self.status(); | ||
|
|
||
| if !(status.is_client_error() || status.is_server_error()) { | ||
| return self | ||
| .error_for_status() | ||
| .map_err(|e| Error::reqwest(context, e)); | ||
| } | ||
|
|
||
| let content_type = self | ||
| .headers() | ||
| .get(header::CONTENT_TYPE) | ||
| .and_then(|v| v.to_str().ok()) | ||
| .unwrap_or(""); | ||
|
|
||
| let (code, message) = if content_type.starts_with("application/json") { | ||
| parse_json_error(self).await | ||
| } else if content_type.starts_with("application/xml") | ||
| || content_type.starts_with("text/xml") | ||
| { | ||
| parse_xml_error(self).await | ||
| } else { | ||
| parse_fallback(self).await | ||
| }; | ||
|
|
||
| Err(Error::BackendResponse { | ||
| context, | ||
| status, | ||
| code, | ||
| message, | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| impl ResponseExt for Result<Response, reqwest::Error> { | ||
| async fn check_error(self, context: &'static str) -> Result<Response> { | ||
| match self { | ||
| Ok(resp) => resp.check_error(context).await, | ||
| Err(e) => Err(Error::reqwest(context, e)), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| async fn parse_json_error(resp: Response) -> (String, String) { | ||
| let status = resp.status(); | ||
| match resp.json::<JsonApiError>().await { | ||
| Ok(body) => { | ||
| let code = body | ||
| .error | ||
| .errors | ||
| .first() | ||
| .map(|e| e.reason.clone()) | ||
| .unwrap_or_else(|| status.as_str().to_owned()); | ||
| (code, body.error.message) | ||
| } | ||
| Err(_) => (status.as_str().to_owned(), status.to_string()), | ||
| } | ||
| } | ||
|
|
||
| async fn parse_xml_error(resp: Response) -> (String, String) { | ||
| let status = resp.status(); | ||
| let bytes = match resp.bytes().await { | ||
| Ok(b) => b, | ||
| Err(_) => return (status.as_str().to_owned(), status.to_string()), | ||
| }; | ||
|
|
||
| match quick_xml::de::from_reader::<_, XmlApiError>(bytes.as_ref()) { | ||
| Ok(body) => (body.code, body.message), | ||
| Err(_) => (status.as_str().to_owned(), status.to_string()), | ||
| } | ||
| } | ||
|
|
||
| async fn parse_fallback(resp: Response) -> (String, String) { | ||
| let status = resp.status(); | ||
| match resp.text().await { | ||
| Ok(text) if !text.is_empty() => { | ||
| let truncated = if text.len() > MAX_ERROR_BODY_LEN { | ||
| let end = text.floor_char_boundary(MAX_ERROR_BODY_LEN); | ||
| format!("{}...(truncated)", &text[..end]) | ||
| } else { | ||
| text | ||
| }; | ||
| (status.as_str().to_owned(), truncated) | ||
| } | ||
| _ => (status.as_str().to_owned(), status.to_string()), | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is a first attempt, though I think we can further improve this.