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

Add custom exception handling for pyrail package #46

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

tjorim
Copy link
Owner

@tjorim tjorim commented Jan 28, 2025

Introduce custom exception classes to improve error handling in the pyrail package, enhancing clarity and control over specific error scenarios.

Summary by CodeRabbit

  • New Features

    • Introduced custom exception classes for more precise error handling
    • Added specific exceptions for rate limit, invalid requests, and not found scenarios
  • Bug Fixes

    • Improved error handling in API client with more informative exception messages

Copy link
Contributor

coderabbitai bot commented Jan 28, 2025

📝 Walkthrough

Walkthrough

The pull request introduces a new exceptions.py module in the pyrail package, defining three custom exception classes: RateLimitError, InvalidRequestError, and NotFoundError. These exceptions are then integrated into the irail.py module to improve error handling. The changes enhance the package's error reporting by providing more specific and informative exceptions for different types of API request errors, replacing previous generic error handling approaches.

Changes

File Change Summary
pyrail/exceptions.py Added three custom exception classes:
- RateLimitError: For rate limit exceeded scenarios
- InvalidRequestError: For invalid request conditions
- NotFoundError: For resource not found errors
pyrail/irail.py Updated _handle_response method to:
- Raise RateLimitError on 429 status code
- Raise InvalidRequestError on 400 status code
- Raise NotFoundError on 404 status code

Sequence Diagram

sequenceDiagram
    participant Client
    participant iRailAPI
    participant ExceptionHandler
    
    Client->>iRailAPI: Send Request
    iRailAPI-->>ExceptionHandler: Check Response Status
    alt Rate Limit Exceeded
        ExceptionHandler->>Client: Raise RateLimitError
    else Invalid Request
        ExceptionHandler->>Client: Raise InvalidRequestError
    else Resource Not Found
        ExceptionHandler->>Client: Raise NotFoundError
    end
Loading

Poem

🐰 Hop, hop, through the error's maze,
Custom exceptions light the ways!
Rate limits, requests gone astray,
Rabbit's code now clearly says
What went wrong today! 🚂✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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
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: 1

🧹 Nitpick comments (4)
pyrail/exceptions.py (1)

1-19: Consider creating a base exception class and enhancing the exception implementations.

The current implementation could be improved by:

  1. Adding a base exception class
  2. Enhancing docstrings with more details
  3. Adding custom initialization for better error messages

Here's a suggested implementation:

 """Module containing custom exception classes for the pyrail package."""
 
+class PyRailError(Exception):
+    """Base exception class for all pyrail exceptions."""
+    pass
 
-class RateLimitError(Exception):
+class RateLimitError(PyRailError):
-    """Raised when the rate limit is exceeded."""
+    """Raised when the API rate limit is exceeded.
+    
+    This exception indicates that too many requests have been made to the API
+    within a short time period. The client should wait before making new requests.
+    """
-    pass
+    def __init__(self, message="API rate limit exceeded"):
+        super().__init__(message)
 
-class InvalidRequestError(Exception):
+class InvalidRequestError(PyRailError):
-    """Raised for invalid requests."""
+    """Raised when the API request is invalid.
+    
+    This exception indicates that the request was malformed or contained
+    invalid parameters that the API cannot process.
+    """
-    pass
+    def __init__(self, message="Invalid API request"):
+        super().__init__(message)
 
-class NotFoundError(Exception):
+class NotFoundError(PyRailError):
-    """Raised when an endpoint is not found."""
+    """Raised when the requested resource is not found.
+    
+    This exception indicates that the requested station, train, or other
+    resource does not exist or could not be found in the system.
+    """
-    pass
+    def __init__(self, message="Resource not found"):
+        super().__init__(message)
pyrail/irail.py (3)

313-314: Remove commented out code.

The old retry logic is commented out and should be removed since it's been replaced with the new exception.

             raise RateLimitError(f"Rate limit exceeded for method {method}")
-            #return await self._do_request(method, args)

316-319: Remove commented out code and enhance error message.

The old None return is commented out and should be removed. Also, consider extracting the error message from the response JSON if available.

             error_message = await response.text()
+            try:
+                error_json = await response.json()
+                error_message = error_json.get('error', error_message)
+            except ValueError:
+                pass
             logger.error("Bad request: %s", error_message)
             raise InvalidRequestError(error_message)
-            #return None

13-13: Consider importing the base exception class.

If you implement the suggested PyRailError base class, update the imports accordingly.

-from pyrail.exceptions import InvalidRequestError, NotFoundError, RateLimitError
+from pyrail.exceptions import (
+    PyRailError,
+    InvalidRequestError,
+    NotFoundError,
+    RateLimitError,
+)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0d15be9 and 64fe38b.

📒 Files selected for processing (2)
  • pyrail/exceptions.py (1 hunks)
  • pyrail/irail.py (2 hunks)
🧰 Additional context used
🪛 GitHub Actions: Run Tests
pyrail/irail.py

[error] 323-323: NotFoundError exception thrown: Stop 'INVALID_STATION' can not be found


[warning] 207-207: PytestDeprecationWarning: The configuration option 'asyncio_default_fixture_loop_scope' is unset

Comment on lines +321 to +324
error_message = await response.text()
logger.error("Endpoint %s not found, response: %s", method, error_message)
raise NotFoundError(error_message)
#return None
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

Fix NotFoundError handling and remove commented code.

The pipeline failure indicates an issue with NotFoundError being thrown for an invalid station. Consider improving the error message to be more specific about the type of resource that wasn't found.

             error_message = await response.text()
+            resource_type = "resource"
+            if "station" in method.lower() or "stop" in error_message.lower():
+                resource_type = "station"
+            elif "vehicle" in method.lower():
+                resource_type = "vehicle"
             logger.error("Endpoint %s not found, response: %s", method, error_message)
-            raise NotFoundError(error_message)
+            raise NotFoundError(f"{resource_type.title()} not found: {error_message}")
-            #return None
📝 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
error_message = await response.text()
logger.error("Endpoint %s not found, response: %s", method, error_message)
raise NotFoundError(error_message)
#return None
error_message = await response.text()
resource_type = "resource"
if "station" in method.lower() or "stop" in error_message.lower():
resource_type = "station"
elif "vehicle" in method.lower():
resource_type = "vehicle"
logger.error("Endpoint %s not found, response: %s", method, error_message)
raise NotFoundError(f"{resource_type.title()} not found: {error_message}")
🧰 Tools
🪛 GitHub Actions: Run Tests

[error] 323-323: NotFoundError exception thrown: Stop 'INVALID_STATION' can not be found

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