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

fix: dump body directly if json indent fails #643

Merged
merged 2 commits into from
Nov 8, 2024
Merged

Conversation

danielgtaylor
Copy link
Owner

@danielgtaylor danielgtaylor commented Nov 7, 2024

Small fix for when the JSON is invalid (or not actually JSON). This makes sure it is still put into the response rather than accidentally dropped.

Summary by CodeRabbit

  • Bug Fixes
    • Improved error handling during JSON indentation to ensure valid output even when formatting fails.
  • New Features
    • Added a test for handling invalid JSON input in the DumpRequest function, enhancing the robustness of the error handling process.

Copy link

coderabbitai bot commented Nov 7, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes in this pull request modify the dumpBody function within the humatest/humatest.go file to improve error handling during the JSON indentation process. The updated implementation checks for errors after attempting to indent JSON data. If an error occurs, it writes the original buffer content instead of the indented version, ensuring a valid response is always returned. The overall structure and functionality of the humatest package remain unchanged, with no modifications to exported or public entity signatures.

Changes

File Change Summary
humatest/humatest.go Enhanced error handling in dumpBody function during JSON indentation.
humatest/humatest_test.go Replaced http.NewRequest with httptest.NewRequest in tests; added TestDumpBodyInvalidJSON to validate handling of invalid JSON.

Possibly related PRs

  • fix: use status code returned from NewError when writing errors #581: The changes in this PR involve error handling in the WriteErr function, which is related to improving error management, similar to the enhancements made to the dumpBody function in the main PR. Both PRs focus on ensuring that errors are handled more robustly in their respective functions.

Poem

In the code where bunnies play,
A change was made to save the day.
When JSON fails, no need to fret,
The original's safe, no need to sweat!
With hops and jumps, our code is bright,
Error handling now feels just right! 🐇✨


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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

codecov bot commented Nov 7, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 92.72%. Comparing base (a74067b) to head (e278647).
Report is 10 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #643      +/-   ##
==========================================
+ Coverage   92.70%   92.72%   +0.01%     
==========================================
  Files          22       22              
  Lines        4879     4891      +12     
==========================================
+ Hits         4523     4535      +12     
  Misses        308      308              
  Partials       48       48              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link

@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: 1

🧹 Outside diff range and nitpick comments (1)
humatest/humatest.go (1)

348-351: Consider adding debug logging for indent failures.

For better debugging capabilities, consider logging the indentation error when it occurs. This would help diagnose issues where the JSON formatting unexpectedly fails.

Here's a suggested improvement:

-		if err := json.Indent(buf, b, "", "  "); err != nil {
-			// Indent failed, so just write the buffer.
-			buf.Write(b)
+		if err := json.Indent(buf, b, "", "  "); err != nil {
+			// Log the error for debugging purposes
+			fmt.Printf("JSON indent failed: %v\n", err)
+			// Fall back to writing the raw buffer
+			buf.Write(b)
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 349-351: humatest/humatest.go#L349-L351
Added lines #L349 - L351 were not covered by tests

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a74067b and 63afc35.

📒 Files selected for processing (1)
  • humatest/humatest.go (1 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
humatest/humatest.go

[warning] 349-351: humatest/humatest.go#L349-L351
Added lines #L349 - L351 were not covered by tests

🔇 Additional comments (1)
humatest/humatest.go (1)

348-351: LGTM! The error handling improvement looks good.

The change correctly handles JSON indentation failures by falling back to the raw buffer content, which aligns with the PR objective.

Let's verify the behavior with some test cases. Run this script to check if we have any existing tests for invalid JSON:

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 349-351: humatest/humatest.go#L349-L351
Added lines #L349 - L351 were not covered by tests

Comment on lines +348 to +351
if err := json.Indent(buf, b, "", " "); err != nil {
// Indent failed, so just write the buffer.
buf.Write(b)
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding test coverage for the error path.

The new error handling code is currently not covered by tests. Consider adding test cases for:

  1. Invalid JSON that fails indentation
  2. Malformed JSON with special characters

Would you like me to help generate test cases for these scenarios?

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 349-351: humatest/humatest.go#L349-L351
Added lines #L349 - L351 were not covered by tests

@danielgtaylor danielgtaylor merged commit 4218123 into main Nov 8, 2024
7 checks passed
@danielgtaylor danielgtaylor deleted the fix-print-response branch November 8, 2024 02:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant