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

Handle resource alias not found error #29

Merged
merged 2 commits into from
Nov 14, 2024
Merged

Conversation

jpeimer
Copy link
Collaborator

@jpeimer jpeimer commented Nov 14, 2024

  • Add an exception for read alias file
  • Add an exception for alias not found
  • Move read alias file to utils

Fix #10
Fix #15

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced two new exception classes for improved error handling: MissingResourceKindAliasError and FailToReadJSONFileError.
    • Added a new utility function for reading aliases from a JSON file, enhancing modularity and error management.
  • Bug Fixes

    • Enhanced error handling in the main function to prevent abrupt program termination and allow for continued user interaction in case of specific errors.

Copy link

coderabbitai bot commented Nov 14, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request introduces two new exception classes in the app/exceptions.py file: MissingResourceKindAliasError and FailToReadJSONFileError. These exceptions enhance error handling in the application, allowing for more graceful management of specific error conditions. Additionally, the main function in app/main.py has been updated to utilize these exceptions, improving the control flow by preventing abrupt program termination and enabling continued user interaction during error scenarios. A new utility function for reading aliases has also been introduced in app/utils.py.

Changes

File Change Summary
app/exceptions.py Added MissingResourceKindAliasError and FailToReadJSONFileError classes with custom initializers and __repr__ methods.
app/main.py Wrapped get_cluster_resources_raw_data in a try block to handle new exceptions, preventing program termination on errors. Modified get_resource_kind_by_alias to raise exceptions instead of calling sys.exit().
app/constants.py Added CONSOLE instance from rich.console and a new constant HOW_TO_UPDATE_ALIASES_MESSAGE.
app/resource_aliases.py Updated fill_api_resources_aliases to use read_aliases_file for improved error handling and imported CONSOLE.
app/utils.py Introduced read_aliases_file function for reading aliases from a JSON file with error handling.

Assessment against linked issues

Objective Addressed Explanation
Implement validation for resource kind in get_cluster_resources_raw_data (10)
Handle cases where no resource kind is found among aliases (10)
Handle cases where resource kind is found, but no YAML exists (10) The implementation does not address the second case.
Implement debug-level logging for exceptions (15) No logging implementation is present in the changes.

Possibly related PRs

  • Handle resource alias not found error #29: This PR introduces the same exception classes (MissingResourceKindAliasError and FailToReadJSONFileError) in app/exceptions.py, which are also added in the main PR, indicating a direct relationship in error handling improvements.

Suggested reviewers

  • myakove

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.

@redhat-qe-bot2
Copy link

Report bugs in Issues

The following are automatically added:

  • Add reviewers from OWNER file (in the root of the repository) under reviewers section.
  • Set PR size label.
  • New issue is created for the PR. (Closed when PR is merged/closed)
  • Run pre-commit if .pre-commit-config.yaml exists in the repo.

Available user actions:

  • To mark PR as WIP comment /wip to the PR, To remove it from the PR comment /wip cancel to the PR.
  • To block merging of PR comment /hold, To un-block merging of PR comment /hold cancel.
  • To mark PR as verified comment /verified to the PR, to un-verify comment /verified cancel to the PR.
    verified label removed on each new commit push.
  • To cherry pick a merged PR comment /cherry-pick <target branch to cherry-pick to> in the PR.
    • Multiple target branches can be cherry-picked, separated by spaces. (/cherry-pick branch1 branch2)
    • Cherry-pick will be started when PR is merged
  • To build and push container image command /build-and-push-container in the PR (tag will be the PR number).
    • You can add extra args to the Podman build command
      • Example: /build-and-push-container --build-arg OPENSHIFT_PYTHON_WRAPPER_COMMIT=<commit_hash>
  • To add a label by comment use /<label name>, to remove, use /<label name> cancel
  • To assign reviewers based on OWNERS file use /assign-reviewers
  • To check if PR can be merged use /check-can-merge
Supported /retest check runs
  • /retest tox: Retest tox
  • /retest python-module-install: Retest python-module-install
  • /retest all: Retest all
Supported labels
  • hold
  • verified
  • wip
  • lgtm

myakove
myakove previously approved these changes Nov 14, 2024
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)
app/exceptions.py (2)

1-7: Consider enhancing the exception class implementation

The implementation is correct and aligns with the PR objectives. However, consider these improvements for better maintainability and usability:

 class MissingResourceKindAliasError(Exception):
+    """Exception raised when a requested resource kind alias is not found.
+
+    Args:
+        requested_kind: The resource kind that was not found in aliases
+    """
     def __init__(self, requested_kind: str) -> None:
+        message = f"Resource kind alias '{requested_kind}' not found"
+        super().__init__(message)
         self.requested_kind = requested_kind
 
     def __repr__(self) -> str:
         return f"Resource kind alias '{self.requested_kind}' not found"
+
+    def __str__(self) -> str:
+        return self.__repr__()

9-14: Enhance error handling and documentation

The implementation is correct but could be enhanced for better error reporting and maintainability:

 class FailToReadJSONFileError(Exception):
+    """Exception raised when a JSON file cannot be read.
+
+    Args:
+        file_name: Path to the JSON file that couldn't be read
+        original_error: Optional underlying error that caused the failure
+    """
-    def __init__(self, file_name: str) -> None:
+    def __init__(self, file_name: str, original_error: Exception = None) -> None:
+        message = f"Failed to read JSON file '{file_name}'"
+        if original_error:
+            message += f": {str(original_error)}"
+        super().__init__(message)
         self.file_name = file_name
+        self.original_error = original_error
 
     def __repr__(self) -> str:
-        return f"Can't read file '{self.file_name}'"
+        return f"Failed to read JSON file '{self.file_name}'"
+
+    def __str__(self) -> str:
+        return self.__repr__()

This enhancement:

  1. Adds comprehensive documentation
  2. Captures the underlying error for better debugging
  3. Provides more specific error messaging
  4. Maintains consistency with Python's exception handling patterns
app/main.py (2)

157-159: Enhance user feedback for better UX

The message when no resources are found could be more descriptive to help users understand why their query returned no results.

Consider this enhancement:

             if not resources_raw_data:
-                CONSOLE.print(f"No resources found for {resource_kind} {resource_name} {namespace_name}")
+                message = f"No resources found for kind '{resource_kind}'"
+                if name:
+                    message += f" with name '{name}'"
+                if namespace:
+                    message += f" in namespace '{namespace}'"
+                CONSOLE.print(f"[yellow]{message}[/yellow]")
                 continue

Line range hint 14-272: Consider centralizing error messages

The error messages are currently scattered throughout the code. Consider centralizing them in a dedicated module (e.g., app/messages.py) to:

  • Maintain consistency in messaging
  • Enable easier updates and translations
  • Reduce duplication

Example structure:

# app/messages.py
class ErrorMessages:
    ALIASES_UPDATE_HELP = "How to update the resource aliases file: {url}"
    INVALID_RESOURCE_KIND = "[bold red]Error:[/bold red] Not valid resource kind '{kind}'"
    NO_RESOURCES_FOUND = "No resources found for kind '{kind}'{name_info}{namespace_info}"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ec8715c and c78671b.

📒 Files selected for processing (2)
  • app/exceptions.py (1 hunks)
  • app/main.py (4 hunks)
🔇 Additional comments (3)
app/exceptions.py (1)

1-14: Verify exception handling implementation

Let's verify that these exceptions are properly caught and handled in the codebase:

✅ Verification successful

Exceptions are properly implemented and handled

The exceptions are well-integrated into the codebase:

  • FailToReadJSONFileError is properly raised in get_resource_kind_by_alias() when there's an issue reading the aliases file, with appropriate error messaging and graceful exit
  • MissingResourceKindAliasError is correctly raised when an invalid resource kind is requested, with helpful user feedback
  • Both exceptions are caught in the main command loop with appropriate error handling:
    • FailToReadJSONFileError triggers system exit
    • MissingResourceKindAliasError continues the loop for new user input
  • The exceptions provide meaningful error messages through their __repr__ implementations
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the implementation of error handling for these exceptions

# Check for exception usage
echo "Checking exception usage:"
rg -l "MissingResourceKindAliasError|FailToReadJSONFileError" --type python

# Check for proper exception handling
echo -e "\nChecking exception handling patterns:"
rg -B 2 -A 2 "try.*:.*\n.*MissingResourceKindAliasError|try.*:.*\n.*FailToReadJSONFileError" --type python

# Look for potential error handling gaps
echo -e "\nChecking for potential missing error handling:"
rg "\.json['\"]?\)" --type python

Length of output: 739


Script:

#!/bin/bash
# Let's try a different approach without relying on file type detection

# Check for exception usage
echo "Checking exception usage:"
rg -l "MissingResourceKindAliasError|FailToReadJSONFileError" 

# Check for proper exception handling with multiline flag
echo -e "\nChecking exception handling patterns:"
rg -U -B 2 -A 2 "try:.*[\n\r\s]+.*(?:MissingResourceKindAliasError|FailToReadJSONFileError)"

# Look for potential error handling gaps
echo -e "\nChecking for JSON file operations:"
rg "\.json"

# Check imports of these exceptions
echo -e "\nChecking imports:"
rg "from.*exceptions.*import.*(?:MissingResourceKindAliasError|FailToReadJSONFileError)"

Length of output: 821


Script:

#!/bin/bash
# Let's examine the actual usage in main.py

echo "Checking main.py content for exception usage:"
cat app/main.py

echo -e "\nChecking aliases.json file operations:"
cat app/constants.py

Length of output: 9765

app/main.py (2)

14-14: LGTM: Clean import of new exception classes

The import statement is well-placed and correctly imports both new exception classes.


261-261: LGTM: Well-implemented exception handling with helpful messages

The exception raising is well-implemented with:

  • Informative error messages that guide users
  • Helpful links for updating aliases
  • Appropriate exception types for different error cases

Also applies to: 272-272

app/main.py Show resolved Hide resolved
@jpeimer
Copy link
Collaborator Author

jpeimer commented Nov 14, 2024

/verified

@jpeimer jpeimer merged commit 9855168 into main Nov 14, 2024
5 checks passed
@jpeimer jpeimer deleted the handle_resource_alias_errors branch November 14, 2024 10:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
6 participants