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

chore: Add unsuccessfull response content logging #1324

Closed
wants to merge 1 commit into from

Conversation

elsand
Copy link
Collaborator

@elsand elsand commented Oct 21, 2024

Description

Related Issue(s)

  • N/A

Verification

  • Your code builds clean without any errors or warnings
  • Manual testing done (required)
  • Relevant automated test added (if you find this hard, leave it and we'll help out)

Documentation

  • Documentation is updated (either in docs-directory, Altinnpedia or a separate linked PR in altinn-studio-docs., if applicable)

Summary by CodeRabbit

  • New Features

    • Introduced enhanced error handling for HTTP responses, improving response validation for POST requests.
    • Added a new extension method to ensure successful status codes with detailed error content.
  • Bug Fixes

    • Improved handling of unsuccessful responses by providing more informative error messages, including truncated content when necessary.

@elsand elsand requested a review from a team as a code owner October 21, 2024 12:01
Copy link
Contributor

coderabbitai bot commented Oct 21, 2024

📝 Walkthrough

Walkthrough

The pull request introduces enhancements to error handling and response validation in the HttpClientExtensions class and adds a new HttpResponseMessageExtensions class. The PostAsJsonEnsuredAsync methods are updated to utilize a new method, EnsureSuccessStatusCodeWithContent, which provides more robust checks for HTTP response content. This new method reads response content and throws exceptions with detailed messages for unsuccessful responses. Overall, the changes aim to improve the reliability of HTTP client operations.

Changes

File Change Summary
src/Digdir.Domain.Dialogporten.Infrastructure/HttpClientExtensions.cs Updated PostAsJsonEnsuredAsync methods to use new response validation logic.
src/Digdir.Domain.Dialogporten.Infrastructure/HttpResponseMessageExtensions.cs Introduced HttpResponseMessageExtensions class with EnsureSuccessStatusCodeWithContent method for enhanced error handling.

Possibly related PRs

Suggested reviewers

  • oskogstad

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (1)
src/Digdir.Domain.Dialogporten.Infrastructure/HttpResponseMessageExtensions.cs (1)

5-5: Consider making MaxContentLength configurable

Hardcoding the MaxContentLength to 1000 may not be flexible for different deployment environments or future requirements. Consider making this value configurable through application settings.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 71698bf and 623a0c0.

📒 Files selected for processing (2)
  • src/Digdir.Domain.Dialogporten.Infrastructure/HttpClientExtensions.cs (1 hunks)
  • src/Digdir.Domain.Dialogporten.Infrastructure/HttpResponseMessageExtensions.cs (1 hunks)
🧰 Additional context used
🔇 Additional comments (2)
src/Digdir.Domain.Dialogporten.Infrastructure/HttpResponseMessageExtensions.cs (1)

31-34: LGTM!

The GetResponseCodeWithReasonPhrase method is well-implemented and handles cases where ReasonPhrase might be null or whitespace.

src/Digdir.Domain.Dialogporten.Infrastructure/HttpClientExtensions.cs (1)

51-52: Enhanced error handling with EnsureSuccessStatusCodeWithContent().

Replacing EnsureSuccessStatusCode() with EnsureSuccessStatusCodeWithContent() improves the logging of unsuccessful response content, aligning with the PR objective.

Comment on lines +14 to +29
var content = await response.Content.ReadAsStringAsync();
if (string.IsNullOrWhiteSpace(content))
{
// This will throw HttpRequestException with the response status code and reason phrase
return response.EnsureSuccessStatusCode();
}

if (content.Length > MaxContentLength)
{
content = content[..MaxContentLength] + "[truncated after " + MaxContentLength + " characters]";
}

throw new HttpRequestException("Response unsuccessful (" + response.GetResponseCodeWithReasonPhrase() +
" with error content: " + content, null, response.StatusCode);

}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Avoid including response content in exception messages to prevent sensitive data leakage

Including the response content in exception messages could inadvertently expose sensitive or confidential information if exceptions are logged or displayed. Consider removing the response content from the exception message and logging it securely instead.

Apply this diff to modify the exception handling:

-        throw new HttpRequestException("Response unsuccessful (" + response.GetResponseCodeWithReasonPhrase() +
-                                       " with error content: " + content, null, response.StatusCode);
+        // Optionally log 'content' securely here
+        throw new HttpRequestException("Response unsuccessful (" + response.GetResponseCodeWithReasonPhrase() + ")", null, response.StatusCode);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
var content = await response.Content.ReadAsStringAsync();
if (string.IsNullOrWhiteSpace(content))
{
// This will throw HttpRequestException with the response status code and reason phrase
return response.EnsureSuccessStatusCode();
}
if (content.Length > MaxContentLength)
{
content = content[..MaxContentLength] + "[truncated after " + MaxContentLength + " characters]";
}
throw new HttpRequestException("Response unsuccessful (" + response.GetResponseCodeWithReasonPhrase() +
" with error content: " + content, null, response.StatusCode);
}
var content = await response.Content.ReadAsStringAsync();
if (string.IsNullOrWhiteSpace(content))
{
// This will throw HttpRequestException with the response status code and reason phrase
return response.EnsureSuccessStatusCode();
}
if (content.Length > MaxContentLength)
{
content = content[..MaxContentLength] + "[truncated after " + MaxContentLength + " characters]";
}
// Optionally log 'content' securely here
throw new HttpRequestException("Response unsuccessful (" + response.GetResponseCodeWithReasonPhrase() + ")", null, response.StatusCode);
}

Comment on lines +14 to +19
var content = await response.Content.ReadAsStringAsync();
if (string.IsNullOrWhiteSpace(content))
{
// This will throw HttpRequestException with the response status code and reason phrase
return response.EnsureSuccessStatusCode();
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Inconsistent exception handling between empty and non-empty content cases

When the response content is empty, the method calls response.EnsureSuccessStatusCode(), which throws an HttpRequestException with standard message formatting. However, when content is present, a new HttpRequestException is thrown with a custom message. This inconsistency may lead to confusion when handling exceptions. Consider standardizing the exception handling mechanism.

Apply this diff to standardize exception handling:

-            return response.EnsureSuccessStatusCode();
+            throw new HttpRequestException("Response unsuccessful (" + response.GetResponseCodeWithReasonPhrase() + ")", null, response.StatusCode);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
var content = await response.Content.ReadAsStringAsync();
if (string.IsNullOrWhiteSpace(content))
{
// This will throw HttpRequestException with the response status code and reason phrase
return response.EnsureSuccessStatusCode();
}
var content = await response.Content.ReadAsStringAsync();
if (string.IsNullOrWhiteSpace(content))
{
// This will throw HttpRequestException with the response status code and reason phrase
throw new HttpRequestException("Response unsuccessful (" + response.GetResponseCodeWithReasonPhrase() + ")", null, response.StatusCode);
}

@@ -48,7 +48,8 @@ public static async Task<HttpResponseMessage> PostAsJsonEnsuredAsync(
configureHeaders?.Invoke(httpRequestMessage.Headers);
configureContentHeaders?.Invoke(httpRequestMessage.Content.Headers);
var response = await client.SendAsync(httpRequestMessage, cancellationToken);
response.EnsureSuccessStatusCode();
await response.EnsureSuccessStatusCodeWithContent();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Det er litt skummelt å logge response body for alle kontekster. Meg bekjent brukes denne extension for mer enn bare altinn auth, og det å logge respons (som kan være sensitiv) som en del av exception er litt så-som-så. Vi kan heller sette "Serilog__MinimumLevel__Override__Digdir.Domain.Dialogporten.Infrastructure.Altinn.Authorization.AltinnAuthorizationClient": "Debug" i stage. Det har jeg gjort gjennom app configuration allerede.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Enig i at dette i utgangspunktet er litt sketch. Vil det å overridde loglevel her gjøre at vi får logga response body?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nei, vi skal (ut i fra koden) få request body som vil si at vi kan reprodusere selv via postman.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Men det viktige er at vi får request body for kun denne konteksten så lenge vi har på debug logging

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, hvis vi skal lene oss på ILogger (som jeg er enig i gir mening), må vi implementere dette et annet sted enn i disse extension metodene. Evt må vi hekte på content i exceptionen på noe vis og hente det ut og logge det et annet sted i pipelinen.

@elsand elsand closed this Oct 23, 2024
@elsand elsand deleted the chore/add-unsuccessful-response-content-logging branch October 23, 2024 14:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Archived in project
Development

Successfully merging this pull request may close these issues.

2 participants