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

Create Tweet Errors #202

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

Create Tweet Errors #202

wants to merge 4 commits into from

Conversation

manudev-1
Copy link

@manudev-1 manudev-1 commented Sep 4, 2024

Description

Context

This PR introduces error handling for the create_tweet function. Currently, the function does not properly handle potential errors that may occur during tweet creation, such as the length of a tweet and the duplication of a tweet in a short period. This update aims to make the function more robust and improve overall reliability.
Currently, the error provided when create_tweet fails is a KeyError exception which is too general to troubleshoot, with this update we try to give more meaningful error to the developer

Changes

  • Added a private function _switch_error
    • _switch_error at the moment manage 2 exception (Duplicated tweet in short period of time, length of the tweet)
    • When error occures but it's not handled program, before crash, print response to make sure that the developer notice the error and can report the known issue
  • Added 2 errors in errors.py

Summary by Sourcery

Implement error handling in the create_tweet function by introducing specific exceptions for duplicate tweets and tweets exceeding maximum length, and adding a mechanism to handle and report unhandled errors.

New Features:

  • Introduce error handling for the create_tweet function to manage specific exceptions such as duplicate tweets and tweets exceeding maximum length.

Enhancements:

  • Add a private function _switch_error to map specific error messages to custom exceptions and print the response for unhandled errors.

Summary by CodeRabbit

  • New Features

    • Improved error handling for tweet creation, providing clearer feedback on specific issues such as duplicates and maximum length exceeded.
    • Introduced new exception classes for better granularity in error reporting during tweet creation.
  • Bug Fixes

    • Enhanced robustness of the tweet creation process by addressing potential error scenarios more effectively.

Copy link

sourcery-ai bot commented Sep 4, 2024

Reviewer's Guide by Sourcery

This pull request implements error handling for the create_tweet function, introducing specific exceptions for duplicate tweets and tweet length issues, and adds a mechanism to print responses for unhandled errors.

File-Level Changes

Change Details Files
Implemented error handling in the create_tweet function
  • Added a private method _switch_error to handle specific tweet creation errors
  • Introduced error checking for empty response data
  • Created a mapping between error messages and custom exception classes
  • Added fallback to print the entire response for unknown errors
twikit/client/client.py
Introduced new custom exception classes for tweet creation errors
  • Added CreateTweetFailed as a base exception for tweet creation errors
  • Created CreateTweetDuplicate exception for duplicate tweets
  • Created CreateTweetMaxLengthReached exception for tweets exceeding maximum length
twikit/errors.py

Tips
  • Trigger a new Sourcery review by commenting @sourcery-ai review on the pull request.
  • Continue your discussion with Sourcery by replying directly to review comments.
  • You can change your review settings at any time by accessing your dashboard:
    • Enable or disable the Sourcery-generated pull request summary or reviewer's guide;
    • Change the review language;
  • You can always contact us if you have any questions or feedback.

Copy link
Contributor

coderabbitai bot commented Sep 4, 2024

Walkthrough

The changes enhance error handling in the Client class within twikit/client/client.py by introducing new exception types and modifying the create_tweet method. A private method, _switch_error, is added to manage specific error scenarios based on response codes from the GraphQL API, improving the clarity and robustness of error reporting during tweet creation.

Changes

Files Change Summary
twikit/client/client.py Enhanced error handling in create_tweet; added _switch_error method for specific error processing.
twikit/errors.py Introduced CreateTweetDuplicate and CreateTweetMaxLengthReached exception classes for improved error management.

Poem

In the meadow, tweets take flight,
With new exceptions shining bright.
A rabbit hops, with joy to share,
For clearer errors show we care!
Let tweets be crafted without dread,
As we leap ahead, our worries shed! 🐇✨


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

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @manudev-1 - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider raising exceptions directly in create_tweet instead of using a private _switch_error method. This would make the error handling more straightforward and easier to follow.
  • The docstring for CreateTweetMaxLengthReached in errors.py is incomplete and should be fixed.
Here's what I looked at during the review
  • 🟡 General issues: 3 issues found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment to tell me if it was helpful.

@@ -4234,3 +4238,16 @@ async def _update_subscriptions(
async def _get_user_state(self) -> Literal['normal', 'bounced', 'suspended']:
response, _ = await self.v11.user_state()
return response['userState']

def _switch_error(
Copy link

Choose a reason for hiding this comment

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

suggestion: Consider refactoring error handling logic

The current implementation of _switch_error mixes different responsibilities. Consider using a dictionary to map error messages to exception types, which would make it easier to maintain and extend in the future.

    def _switch_error(self, response: dict) -> None:
        error_map = {
            'InvalidCredentials': InvalidCredentialsError,
            'InvalidToken': InvalidTokenError,
            'Unauthorized': UnauthorizedError,
            # Add more mappings as needed
        }
        error_type = response.get('error', {}).get('type')
        if error_type in error_map:
            raise error_map[error_type](response['error']['message'])
        raise TwikitError(response['error']['message'])

elif "Tweet needs to be a bit shorter" in response['errors']['message']:
raise CreateTweetMaxLengthReached("Tweet needs to be a bit shorter")
# * Print <response> to reach unknown errors in 2024-09-04
print(response)
Copy link

Choose a reason for hiding this comment

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

suggestion: Replace print with logging for unknown errors

Using print for logging unknown errors is not ideal for production code. Consider using a proper logging mechanism instead, which would provide more control over log levels and output destinations.

import logging

logger = logging.getLogger(__name__)

# ... (in the relevant function)
logger.error(f"Unknown error occurred: {response}")

twikit/errors.py Outdated

class CreateTweetMaxLengthReached(CreateTweetFailed):
"""
Exception raised when create_tweet try to c.
Copy link

Choose a reason for hiding this comment

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

issue: Complete the docstring for CreateTweetMaxLengthReached

The docstring for CreateTweetMaxLengthReached is incomplete. Please finish the sentence to clearly explain when this exception is raised.

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

Outside diff range, codebase verification and nitpick comments (1)
twikit/client/client.py (1)

Line range hint 1-1: TODO: Add tests

It's important to have tests for the code to ensure its correctness and maintainability. Please consider adding tests for this module.

Do you need any help with writing the tests? I can provide guidance or examples if needed. Let me know if you'd like me to open a GitHub issue to track this task.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 6d19016 and 769db25.

Files selected for processing (2)
  • twikit/client/client.py (3 hunks)
  • twikit/errors.py (1 hunks)
Additional comments not posted (2)
twikit/errors.py (2)

97-100: LGTM!

The code changes are approved.


102-105: LGTM!

The code changes are approved.

twikit/errors.py Outdated
Comment on lines 107 to 110
class CreateTweetMaxLengthReached(CreateTweetFailed):
"""
Exception raised when create_tweet try to c.
"""
Copy link
Contributor

Choose a reason for hiding this comment

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

Update the docstring to provide a clear description of the class.

The docstring is incomplete and does not provide a clear description of the class.

Apply this diff to update the docstring:

 class CreateTweetMaxLengthReached(CreateTweetFailed):
     """
-    Exception raised when create_tweet try to c.
+    Exception raised when create_tweet tries to create a tweet that exceeds the maximum allowed length.
     """
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
class CreateTweetMaxLengthReached(CreateTweetFailed):
"""
Exception raised when create_tweet try to c.
"""
class CreateTweetMaxLengthReached(CreateTweetFailed):
"""
Exception raised when create_tweet tries to create a tweet that exceeds the maximum allowed length.
"""

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: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 769db25 and af07ab6.

Files selected for processing (2)
  • twikit/client/client.py (3 hunks)
  • twikit/errors.py (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • twikit/client/client.py
  • twikit/errors.py

@manudev-1
Copy link
Author

@sourcery-ai review

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @manudev-1 - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider refactoring the _switch_error method to use a more robust approach for error handling, possibly using error codes instead of string matching. This would make the code less brittle and easier to maintain as new error types are added.
  • Replace the print statement for unknown errors with proper logging. This will make it easier to manage and control error output in different environments.
  • Instead of using a TODO comment with a specific date, consider using your project's issue tracking system to manage future tasks and improvements.
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment to tell me if it was helpful.

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: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between af07ab6 and 426b138.

Files selected for processing (1)
  • twikit/client/client.py (3 hunks)
Files skipped from review as they are similar to previous changes (1)
  • twikit/client/client.py

@manudev-1 manudev-1 mentioned this pull request Sep 5, 2024
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: 3

🧹 Outside diff range and nitpick comments (1)
twikit/client/client.py (1)

1243-1244: Safely access 'data' key in response to prevent potential KeyError

The condition if not response['data']: assumes that response always contains the 'data' key. If 'data' is not present, this will raise a KeyError. Consider using if not response.get('data'): to handle cases where 'data' might be missing.

Apply this diff to safely check for 'data' in the response:

-if not response['data']:
+if not response.get('data'):
    self._switch_error(response)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 426b138 and a57a382.

📒 Files selected for processing (1)
  • twikit/client/client.py (3 hunks)

Comment on lines +4253 to +4255
message = response.get('errors', [])[0].get('message', '')
error_msg: str = message[message.index(": ")+2:message.index(". ")]

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

Improve error message parsing to prevent exceptions

Extracting error_msg using string slicing with message.index can raise a ValueError if the expected substrings ": " or ". " are not found in the message. This can occur if the error message format changes or is different than expected. Consider using safer methods like str.partition, str.split, or handling exceptions to avoid unexpected crashes.

Apply this diff to make error parsing more robust:

 message = response.get('errors', [])[0].get('message', '')
-error_msg: str = message[message.index(": ")+2:message.index(". ")]
+colon_index = message.find(": ")
+period_index = message.find(". ")
+if colon_index != -1 and period_index != -1 and colon_index < period_index:
+    error_msg = message[colon_index + 2 : period_index]
+else:
+    error_msg = message
📝 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
message = response.get('errors', [])[0].get('message', '')
error_msg: str = message[message.index(": ")+2:message.index(". ")]
message = response.get('errors', [])[0].get('message', '')
colon_index = message.find(": ")
period_index = message.find(". ")
if colon_index != -1 and period_index != -1 and colon_index < period_index:
error_msg = message[colon_index + 2 : period_index]
else:
error_msg = message

Comment on lines +4253 to +4258
message = response.get('errors', [])[0].get('message', '')
error_msg: str = message[message.index(": ")+2:message.index(". ")]

error_code = response.get('errors', [])[0].get('extensions', {}).get('code', '')
if error_code in error_map:
raise error_map[error_code](error_msg)
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

Check for empty 'errors' list in response to avoid IndexError

The code assumes that response['errors'] contains at least one error. If the errors list is empty, accessing [0] will raise an IndexError. To prevent this, check if the list has elements before accessing the first one.

Apply this diff to safely access the error information:

-errors = response.get('errors', [])[0]
+errors = response.get('errors', [])
+if not errors:
+    # Handle case where errors list is empty
+    return
+error_info = errors[0]
-message = response.get('errors', [])[0].get('message', '')
+message = error_info.get('message', '')
+error_code = error_info.get('extensions', {}).get('code', '')

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +4256 to +4258
error_code = response.get('errors', [])[0].get('extensions', {}).get('code', '')
if error_code in error_map:
raise error_map[error_code](error_msg)
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

Ensure error codes are consistently typed for correct mapping

The error_code extracted from the response is likely a string, whereas the keys in error_map are integers. This can cause the condition if error_code in error_map: to fail even when the code exists in the map. Consider converting error_code to an integer or changing the keys in error_map to strings to ensure proper exception handling.

Apply this diff to ensure consistent data types:

 error_map = {
-    186: CreateTweetDuplicate,
-    187: CreateTweetMaxLengthReached
+    '186': CreateTweetDuplicate,
+    '187': CreateTweetMaxLengthReached
 }

 error_code = response.get('errors', [])[0].get('extensions', {}).get('code', '')

Committable suggestion skipped: line range outside the PR's diff.

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