Skip to content

Conversation

@vearne
Copy link
Owner

@vearne vearne commented Aug 4, 2025

Summary by CodeRabbit

  • Refactor

    • Improved panic recovery to provide more detailed panic information, including both the error value and stack trace, for better error logging and diagnostics.
    • Updated the panic handler to log structured panic details separately.
  • New Features

    • Introduced a new structured format for panic information, enhancing clarity in error reporting.

@coderabbitai
Copy link

coderabbitai bot commented Aug 4, 2025

Walkthrough

The changes introduce a new PanicInfo struct to encapsulate both the panic value and stack trace in a structured way. Panic recovery logic is updated to use this struct throughout, including in the middleware and goroutine recovery. The /panic route handler is refactored to extract the panic-inducing logic into a separate function.

Changes

Cohort / File(s) Change Summary
Panic Recovery Struct & Channel Refactor
timeout.go
Introduces PanicInfo struct to hold panic value and stack trace; updates recovery logic to use this struct and a renamed channel. Removes "fmt" import.
Middleware & Handler Refactor
example/panic/panic.go
Updates recovery middleware to use PanicInfo, logging value and stack separately; extracts division-by-zero code into new dive() function for /panic route.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Router
    participant Middleware
    participant Handler
    participant Goroutine

    Client->>Router: HTTP request to /panic
    Router->>Middleware: Pass request
    Middleware->>Handler: Call handler in goroutine
    Handler->>Goroutine: Execute dive() (division by zero)
    Goroutine-->>Handler: Panic occurs
    Handler-->>Middleware: PanicInfo{Value, Stack} sent via channel
    Middleware->>Middleware: Recover panic, log Value and Stack
    Middleware-->>Client: Return error response with panic value
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

In code where panics used to roam,
Now structs bring all the details home.
With PanicInfo in our paws,
We log the stack without a pause.
Dive deep, dear handler, don't you fear—
Recovery's smarter this new year!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/stack

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
  • 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 explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this 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.

@vearne vearne merged commit a2f7dc1 into master Aug 4, 2025
2 checks passed
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: 2

🧹 Nitpick comments (2)
timeout.go (1)

69-69: Channel type should match the data being sent.

The channel is declared as chan any but exclusively receives PanicInfo structs. Consider using a more specific type for better type safety.

-panicInfoChan := make(chan any, 1)
+panicInfoChan := make(chan PanicInfo, 1)
example/panic/panic.go (1)

23-23: Fix typo in log message.

There's a typo in the log message: "unknow" should be "unknown".

-			log.Printf("unknow error:%v\n", info.Value)
+			log.Printf("unknown error:%v\n", info.Value)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 59d9713 and 9f5f866.

📒 Files selected for processing (2)
  • example/panic/panic.go (2 hunks)
  • timeout.go (3 hunks)
🔇 Additional comments (5)
timeout.go (3)

28-31: Well-structured panic information encapsulation.

The PanicInfo struct effectively encapsulates both the panic value and stack trace in a structured format. The JSON tags are appropriate for serialization scenarios.


73-76: Improved panic data structure.

The panic recovery now properly encapsulates both the panic value and stack trace in a structured format, which is a significant improvement over string formatting.


86-87: PanicInfo propagation verified.

Upstream recover handlers already handle the structured PanicInfo correctly:

  • In example/panic/panic.go, the recovered panic is type-asserted to timeout.PanicInfo and its fields are logged.
  • In timeout_test.go, fmt.Sprintf("%v", p) will format the PanicInfo struct without error.

No further changes are needed.

example/panic/panic.go (2)

47-47: Good refactoring for separation of concerns.

Extracting the panic-inducing logic into a separate dive() function improves code organization and makes the panic trigger more explicit.


52-55: Function serves its purpose well.

The dive() function clearly demonstrates division by zero panic behavior for testing purposes.

Comment on lines +22 to +24
info := p.(timeout.PanicInfo)
log.Printf("unknow error:%v\n", info.Value)
log.Printf("stack:%v\n", info.Stack)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add type assertion safety check.

The type assertion p.(timeout.PanicInfo) will panic if the recovered value is not a PanicInfo struct. This could happen if panics originate from other parts of the application.

-			info := p.(timeout.PanicInfo)
-			log.Printf("unknow error:%v\n", info.Value)
-			log.Printf("stack:%v\n", info.Stack)
+			if info, ok := p.(timeout.PanicInfo); ok {
+				log.Printf("unknow error:%v\n", info.Value)
+				log.Printf("stack:%v\n", info.Stack)
+			} else {
+				log.Printf("unknow error:%v\n", p)
+				log.Printf("stack: not available\n")
+			}
📝 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
info := p.(timeout.PanicInfo)
log.Printf("unknow error:%v\n", info.Value)
log.Printf("stack:%v\n", info.Stack)
if info, ok := p.(timeout.PanicInfo); ok {
log.Printf("unknow error:%v\n", info.Value)
log.Printf("stack:%v\n", info.Stack)
} else {
log.Printf("unknow error:%v\n", p)
log.Printf("stack: not available\n")
}
🤖 Prompt for AI Agents
In example/panic/panic.go around lines 22 to 24, the type assertion
p.(timeout.PanicInfo) is unsafe and can cause a panic if p is not of type
timeout.PanicInfo. Modify the code to use the two-value form of type assertion
to check if the assertion succeeded before accessing info. Only log the details
if the assertion is successful; otherwise, handle the unexpected type safely to
avoid panics.

log.Printf("unknow error:%v\n", info.Value)
log.Printf("stack:%v\n", info.Stack)
c.AbortWithStatusJSON(http.StatusInternalServerError,
errResponse{Code: -1, Msg: fmt.Sprintf("unknow error:%v", p)})
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Inconsistent panic value in response message.

The response message uses the original panic value p instead of info.Value. This creates inconsistency between what's logged and what's returned to the client.

-				c.AbortWithStatusJSON(http.StatusInternalServerError,
-					errResponse{Code: -1, Msg: fmt.Sprintf("unknow error:%v", p)})
+				var panicValue any = p
+				if info, ok := p.(timeout.PanicInfo); ok {
+					panicValue = info.Value
+				}
+				c.AbortWithStatusJSON(http.StatusInternalServerError,
+					errResponse{Code: -1, Msg: fmt.Sprintf("unknow error:%v", panicValue)})
🤖 Prompt for AI Agents
In example/panic/panic.go at line 26, the panic response message uses the
original panic value `p` instead of the consistent `info.Value`. Update the
response message to use `info.Value` to ensure the returned message matches the
logged panic information.

@vearne vearne deleted the feat/stack branch September 29, 2025 07:30
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.

2 participants