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: Using the Recommended Error Determination #1546

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from

Conversation

songzhibin97
Copy link
Contributor

@songzhibin97 songzhibin97 commented Oct 21, 2024

Purpose or design rationale of this PR

Reference: https://go.dev/blog/go1.13-errors
Avoid using the equals sign to determine the wrong way

PR title

Your PR title must follow conventional commits (as we are doing squash merge for each PR), so it must start with one of the following types:

  • build: Changes that affect the build system or external dependencies (example scopes: yarn, eslint, typescript)
  • ci: Changes to our CI configuration files and scripts (example scopes: vercel, github, cypress)
  • docs: Documentation-only changes
  • feat: A new feature
  • fix: A bug fix
  • perf: A code change that improves performance
  • refactor: A code change that doesn't fix a bug, or add a feature, or improves performance
  • style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
  • test: Adding missing tests or correcting existing tests

Deployment tag versioning

Has tag in common/version.go been updated or have you added bump-version label to this PR?

  • No, this PR doesn't involve a new deployment, git tag, docker image tag
  • Yes

Breaking change label

Does this PR have the breaking-change label?

  • No, this PR is not a breaking change
  • Yes

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling across multiple methods to enhance robustness and compatibility with wrapped errors.
    • Updated error messages in several methods for better clarity and traceability during database updates.
  • Chores

    • Added import statements for the errors package to facilitate improved error handling practices.

Copy link

coderabbitai bot commented Oct 21, 2024

Walkthrough

The changes introduced in this pull request primarily focus on enhancing error handling across multiple files within the orm package. The errors package has been imported to facilitate improved error checks, particularly for gorm.ErrRecordNotFound, which have been updated to use errors.Is(). This modification increases the robustness of error management in various methods while maintaining existing functionality and control flow. Additionally, some methods have been updated to provide more detailed error messages, improving traceability.

Changes

File Path Change Summary
bridge-history-api/internal/orm/batch_event.go Added errors import; updated error checks in GetBatchEventSyncedHeightInDB, GetLastUpdatedFinalizedBlockHeight, and GetUnupdatedFinalizedBatchesLEBlockHeight to use errors.Is().
bridge-history-api/internal/orm/cross_message.go Added errors import; updated error checks in GetMessageSyncedHeightInDB, GetL2LatestFinalizedWithdrawal, and GetL2WithdrawalsByBlockRange to use errors.Is().
coordinator/internal/orm/prover_block_list.go Updated error check in IsPublicKeyBlocked method to use errors.Is().
coordinator/internal/orm/prover_task.go Updated error check in IsProverAssigned method to use errors.Is().
rollup/internal/orm/bundle.go Updated error checks in getLatestBundle and GetFirstPendingBundle methods to use errors.Is(). Added detailed error messages in UpdateFinalizeTxHashAndRollupStatus, UpdateProvingStatus, UpdateRollupStatus, and UpdateProofAndProvingStatusByHash methods.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ORM
    participant Database

    Client->>ORM: Request for data
    ORM->>Database: Query for data
    Database-->>ORM: Return data or error
    ORM->>ORM: Check for gorm.ErrRecordNotFound
    ORM->>ORM: Use errors.Is() for error handling
    ORM-->>Client: Return data or error
Loading

🐇 "In the code where errors reside,
A little change, now we take pride.
With errors.Is we check with glee,
No more worries, just code harmony!
Robust and clear, our paths align,
Hopping forward, all will be fine!" 🐇

Possibly related PRs

  • fix(rollup): sender use pending block base fee #1556: The changes in rollup/internal/controller/sender/sender.go involve updating error handling for retrieving block headers, which is related to the overall theme of improving error handling seen in the main PR's modifications to error checks in batch_event.go.
  • fix(rollup-relayer): update finalize status atomically #1558: The modifications in rollup/internal/controller/relayer/l2_relayer.go enhance error handling and transaction management, aligning with the main PR's focus on improving error handling practices in the batch_event.go file.

Suggested reviewers

  • georgehao
  • colinlyguo
  • roylou

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c7c5201 and 88480b6.

📒 Files selected for processing (1)
  • rollup/internal/orm/bundle.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • rollup/internal/orm/bundle.go

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

@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 (4)
bridge-history-api/internal/orm/batch_event.go (3)

Line range hint 49-53: LGTM: Improved error handling.

The update to use errors.Is() for checking gorm.ErrRecordNotFound is a good practice. It aligns with Go 1.13+ error handling recommendations.

Consider updating the error message to be more specific:

return 0, fmt.Errorf("failed to get batch synced height in db: %w", err)

This change removes the redundant "error:" text, as %w already includes the error string.


Line range hint 66-70: LGTM: Consistent error handling improvement.

The update to use errors.Is() for checking gorm.ErrRecordNotFound is consistent with the previous function and follows good practices.

Consider updating the error message for consistency:

return 0, fmt.Errorf("failed to get last updated finalized block height: %w", err)

This change removes the redundant "error:" text, as %w already includes the error string.


Inconsistent Error Message Regarding Block Height Comparison

The error message in bridge-history-api/internal/logic/event_update.go uses >= instead of <=, which is inconsistent with the GetUnupdatedFinalizedBatchesLEBlockHeight function's logic.

  • Update the error message to use <= to match the function's behavior:

    log.Error("failed to get unupdated finalized batches <= block height", "error", err)
🔗 Analysis chain

Line range hint 85-89: LGTM: Consistent error handling improvement with minor suggestions.

The update to use errors.Is() for checking gorm.ErrRecordNotFound is consistent with the previous functions and follows good practices.

Consider the following improvements:

  1. Update the error message for consistency and accuracy:
return nil, fmt.Errorf("failed to get unupdated finalized batches <= block height: %w", err)

This change removes the redundant "error:" text and corrects ">=" to "<=" to match the function name.

  1. Consider renaming the function to GetUnupdatedFinalizedBatchesLTEBlockHeight for clarity, as it includes batches with end block numbers less than or equal to the given height.

To ensure the function name accurately reflects its behavior, let's verify the SQL query:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the SQL query in GetUnupdatedFinalizedBatchesLEBlockHeight

# Test: Search for the SQL query in the function
rg -A 10 'GetUnupdatedFinalizedBatchesLEBlockHeight'

Length of output: 2673

bridge-history-api/internal/orm/cross_message.go (1)

Line range hint 88-92: LGTM: Improved error handling.

The update to use errors.Is(err, gorm.ErrRecordNotFound) is a good improvement in error handling. It correctly identifies wrapped errors and aligns with Go's recommended practices.

For consistency, consider updating the error message in the fmt.Errorf call to use %v for the error:

-		return 0, fmt.Errorf("failed to get latest processed height, type: %v, error: %w", messageType, err)
+		return 0, fmt.Errorf("failed to get latest processed height, type: %v, error: %v", messageType, err)

This change would make the error formatting consistent with other error messages in the file.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 41ce22b and d5ded46.

📒 Files selected for processing (5)
  • bridge-history-api/internal/orm/batch_event.go (4 hunks)
  • bridge-history-api/internal/orm/cross_message.go (4 hunks)
  • coordinator/internal/orm/prover_block_list.go (2 hunks)
  • coordinator/internal/orm/prover_task.go (2 hunks)
  • rollup/internal/orm/bundle.go (1 hunks)
🧰 Additional context used
🔇 Additional comments (15)
coordinator/internal/orm/prover_block_list.go (1)

69-69: Excellent update to error handling!

The change from direct comparison to errors.Is(err, gorm.ErrRecordNotFound) is a great improvement. This approach aligns with Go's recommended practices for error handling since Go 1.13. It allows for more robust error checking, especially when dealing with wrapped errors.

This modification enhances the code's reliability without altering the method's overall logic or control flow. Well done!

bridge-history-api/internal/orm/batch_event.go (2)

5-5: LGTM: Import of errors package.

The addition of the errors package import is correct and necessary for the updated error handling using errors.Is().


Line range hint 1-150: Overall: Consistent improvement in error handling.

The changes in this file successfully implement the recommended error determination practices using errors.Is(). This update enhances the robustness of error handling across multiple functions without altering their core logic. The consistency of these changes contributes to improved code quality and maintainability.

While the primary objectives of the PR have been met, there are minor opportunities for further refinement in error messages and function naming for increased clarity and consistency.

Great job on implementing these improvements!

coordinator/internal/orm/prover_task.go (3)

5-5: LGTM: Import of errors package.

The addition of the errors package import is appropriate and necessary for the updated error handling in the IsProverAssigned method.


64-64: LGTM: Improved error checking in IsProverAssigned.

The update to use errors.Is(err, gorm.ErrRecordNotFound) instead of direct comparison is a good improvement. This change:

  1. Aligns with Go 1.13+ best practices for error handling.
  2. Provides more robust error checking, capable of identifying wrapped errors.
  3. Maintains the existing functionality and control flow of the method.

This modification enhances the code's reliability without introducing any breaking changes.


Line range hint 1-284: Summary of changes in prover_task.go

The changes in this file improve error handling in the IsProverAssigned method by adopting the recommended practices for error determination in Go 1.13+. The modifications are:

  1. Addition of the errors package import.
  2. Update of the error check in IsProverAssigned to use errors.Is().

These changes enhance the robustness of error handling without altering the overall functionality of the ProverTask struct or its methods. The improvements are consistent with similar updates in other files mentioned in the PR summary.

rollup/internal/orm/bundle.go (7)

70-73: Improved error handling in getLatestBundle

The changes in this function align with the PR objective of using recommended error determination. The use of errors.Is() for checking gorm.ErrRecordNotFound is a best practice. The error message has also been improved for better traceability.


Line range hint 134-138: Enhanced error handling in GetFirstPendingBundle

The changes in this function are consistent with the PR objective. The use of errors.Is() for checking gorm.ErrRecordNotFound is a recommended practice. The error message has been improved to provide more context, which will aid in debugging and traceability.


Line range hint 220-222: Improved error message in UpdateFinalizeTxHashAndRollupStatus

The error message has been enhanced to include more context (bundle hash, status, and finalizeTxHash). This improvement will greatly aid in debugging and traceability, aligning with the overall goal of enhancing error handling in the codebase.


Line range hint 246-248: Enhanced error message in UpdateProvingStatus

The error message now includes additional context (bundle hash and status). This improvement enhances debugging capabilities and error traceability, which is in line with the overall objective of refining error handling in the codebase.


Line range hint 264-266: Improved error message in UpdateRollupStatus

The error message has been enhanced to include additional context (bundle hash and status). This improvement will facilitate easier debugging and better error traceability, which aligns with the overall goal of enhancing error handling in the codebase.


Line range hint 290-292: Enhanced error message in UpdateProofAndProvingStatusByHash

The error message now includes the bundle hash, which provides more context for debugging. This improvement aligns with the overall objective of enhancing error handling and traceability in the codebase.


Line range hint 1-293: Overall improvements in error handling and messaging

The changes in this file consistently enhance error handling and improve error messages across multiple functions. These improvements include:

  1. Using errors.Is() for checking gorm.ErrRecordNotFound, which aligns with Go's recommended practices for error determination.
  2. Adding more context to error messages, such as including bundle hashes, statuses, and other relevant information.

These changes will significantly improve debugging capabilities and error traceability throughout the codebase. The modifications are in line with the PR objectives and represent a positive step towards more robust error management.

bridge-history-api/internal/orm/cross_message.go (2)

5-5: LGTM: Import of errors package.

The addition of the errors package import is appropriate for the new error handling approach using errors.Is(). This change aligns with the PR objectives to improve error determination.


112-115: LGTM: Improved error handling.

The update to use errors.Is(err, gorm.ErrRecordNotFound) is a good improvement in error handling. It correctly identifies wrapped errors and aligns with Go's recommended practices.

bridge-history-api/internal/orm/cross_message.go Outdated Show resolved Hide resolved
@Thegaram Thegaram requested a review from georgehao October 21, 2024 16:28
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.

3 participants