-
Notifications
You must be signed in to change notification settings - Fork 185
chore: enhance exception type safety and context #1594
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
Open
Adityarya11
wants to merge
6
commits into
hiero-ledger:main
Choose a base branch
from
Adityarya11:fix/enhance-exception-typing#1504
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+240
−62
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
9017bed
chore: enhance exception type safety and context #1504
Adityarya11 a60e0a9
fix: Added max_attempt_error and precheck_error examples
Adityarya11 717123c
fix: Fixed the agruement to accept the last_error as str as well.
Adityarya11 1619bf7
Merge branch 'main' into fix/enhance-exception-typing#1504
Adityarya11 93d2c6d
Merge branch 'main' into fix/enhance-exception-typing#1504
Adityarya11 b6d9c98
Merge branch 'main' into fix/enhance-exception-typing#1504
Adityarya11 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| #!/usr/bin/env python3 | ||
| """ | ||
| Example demonstrating how to handle MaxAttemptsError in the Hiero SDK. | ||
|
|
||
| run: | ||
| uv run examples/errors/max_attempts_error.py | ||
| python examples/errors/max_attempts_error.py | ||
| """ | ||
|
|
||
| from hiero_sdk_python import ( | ||
| Client, | ||
| TransactionGetReceiptQuery, | ||
| TransactionId, | ||
| ) | ||
| from hiero_sdk_python.exceptions import MaxAttemptsError | ||
|
|
||
| def main() -> None: | ||
| # Initialize the client | ||
| client = Client.from_env() | ||
| operator_id = client.operator_account_id | ||
|
|
||
| # Configure client to fail quickly | ||
| # This sets the maximum number of attempts for any request to 1 | ||
| client.max_attempts = 1 | ||
|
|
||
| print("Attempting to fetch receipt with restricted max attempts...") | ||
|
|
||
| # We generate a random transaction ID that definitely doesn't exist. | ||
| # The network would normally return RECEIPT_NOT_FOUND, but depending on the | ||
| # node's state or if we simulate a network blip, the SDK's retry mechanism kicks in. | ||
| # By forcing max_attempts=1, we prevent retries. | ||
| # Note: Triggering a pure MaxAttemptsError usually requires a timeout or busy node. | ||
| # This example demonstrates the structure of handling the error. | ||
|
|
||
| # Using a generated TransactionId | ||
| tx_id = TransactionId.generate(operator_id) | ||
|
|
||
| try: | ||
| TransactionGetReceiptQuery().set_transaction_id(tx_id).execute(client) | ||
| print("Query finished (unexpected for this example test).") | ||
|
|
||
| except MaxAttemptsError as e: | ||
| print("\nCaught MaxAttemptsError!") | ||
| print(f"Node ID: {e.node_id}") | ||
| print(f"Message: {e.message}") | ||
| print("This error means the SDK gave up after reaching the maximum number of retry attempts.") | ||
|
|
||
| except Exception as e: | ||
| # Note: In a real network test with a made-up ID, we might get ReceiptStatusError | ||
| # or PrecheckError (RECEIPT_NOT_FOUND). MaxAttemptsError typically happens | ||
| # on network timeouts or BUSY responses. | ||
| print(f"\nCaught unexpected error (expected for this specific simulation): {type(e).__name__}") | ||
| print(f"Details: {e}") | ||
| print("\n(To verify MaxAttemptsError logic, this example relies on the client's retry configuration)") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| #!/usr/bin/env python3 | ||
| """ | ||
| Example demonstrating how to handle PrecheckError in the Hiero SDK. | ||
|
|
||
| run: | ||
| uv run examples/errors/precheck_error.py | ||
| python examples/errors/precheck_error.py | ||
| """ | ||
|
|
||
| from hiero_sdk_python.exceptions import PrecheckError | ||
| from hiero_sdk_python import ( | ||
| Client, | ||
| TransferTransaction, | ||
| ResponseCode, | ||
| AccountId | ||
| ) | ||
|
|
||
| def main() -> None: | ||
| # Initialize the client | ||
| client = Client.from_env() | ||
| operator_id = client.operator_account_id | ||
| operator_key = client.operator_private_key | ||
|
|
||
| print("Creating transaction with invalid parameters to force PrecheckError...") | ||
|
|
||
| # Create a simple transfer transaction | ||
| # To trigger a PrecheckError, we set the transaction valid duration to 0. | ||
| # The node's precheck validation requires a valid duration, so this will fail immediately. | ||
| transaction = ( | ||
| TransferTransaction() | ||
| .add_hbar_transfer(operator_id, -1) | ||
| .add_hbar_transfer(AccountId(0, 0, 3), 1) | ||
| ) | ||
|
|
||
| # Set the invalid duration directly on the attribute | ||
| transaction.transaction_valid_duration = 0 | ||
|
|
||
| transaction = ( | ||
| transaction | ||
| .freeze_with(client) | ||
| .sign(operator_key) | ||
| ) | ||
|
|
||
|
|
||
| try: | ||
| print("Executing transaction...") | ||
| transaction.execute(client) | ||
| print("Transaction unexpectedly succeeded (this should not happen).") | ||
|
|
||
| except PrecheckError as e: | ||
| print("\nCaught PrecheckError!") | ||
| # This should print: Status: INVALID_TRANSACTION_DURATION (ResponseCode) | ||
| print(f"Status: {e.status} ({ResponseCode(e.status).name})") | ||
| print(f"Transaction ID: {e.transaction_id}") | ||
| print("This error means the transaction failed validation at the node *before* reaching consensus.") | ||
|
|
||
| except Exception as e: | ||
| print(f"\nAn unexpected error occurred: {type(e).__name__}: {e}") | ||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| import pytest | ||
| from unittest.mock import Mock | ||
| from hiero_sdk_python.exceptions import PrecheckError, MaxAttemptsError, ReceiptStatusError | ||
| from hiero_sdk_python.response_code import ResponseCode | ||
|
|
||
| pytestmark = pytest.mark.unit | ||
|
|
||
| def test_precheck_error_typing_and_defaults(): | ||
| """Test PrecheckError with and without optional arguments.""" | ||
| # Mock TransactionId | ||
| tx_id_mock = Mock() | ||
| tx_id_mock.__str__ = Mock(return_value="[email protected]") | ||
|
|
||
| # Case 1: All arguments provided | ||
| err = PrecheckError(ResponseCode.INVALID_TRANSACTION, tx_id_mock, "Custom error") | ||
| assert err.status == ResponseCode.INVALID_TRANSACTION | ||
| assert err.transaction_id is tx_id_mock | ||
| assert str(err) == "Custom error" | ||
| assert repr(err) == f"PrecheckError(status={ResponseCode.INVALID_TRANSACTION}, transaction_id={tx_id_mock})" | ||
|
|
||
| # Case 2: Default message generation | ||
| err_default = PrecheckError(ResponseCode.INVALID_TRANSACTION, tx_id_mock) | ||
| expected_msg = "Transaction failed precheck with status: INVALID_TRANSACTION (1), transaction ID: [email protected]" | ||
| assert str(err_default) == expected_msg | ||
|
|
||
| def test_max_attempts_error_typing(): | ||
| """Test MaxAttemptsError with required and optional arguments.""" | ||
| # Case 1: With last_error | ||
| inner_error = ValueError("Connection failed") | ||
| err = MaxAttemptsError("Max attempts reached", "0.0.3", inner_error) | ||
| assert err.node_id == "0.0.3" | ||
| assert err.last_error is inner_error | ||
| assert "Max attempts reached" in str(err) | ||
| assert "Connection failed" in str(err) | ||
|
|
||
| # Case 2: Without last_error | ||
| err_simple = MaxAttemptsError("Just failed", "0.0.4") | ||
| assert str(err_simple) == "Just failed" | ||
|
|
||
| def test_receipt_status_error_typing(): | ||
| """Test ReceiptStatusError initialization.""" | ||
| tx_id_mock = Mock() | ||
| receipt_mock = Mock() | ||
|
|
||
| # Case 1: Default message | ||
| err = ReceiptStatusError(ResponseCode.RECEIPT_NOT_FOUND, tx_id_mock, receipt_mock) | ||
| assert err.status == ResponseCode.RECEIPT_NOT_FOUND | ||
| assert err.transaction_receipt is receipt_mock | ||
| assert "RECEIPT_NOT_FOUND" in str(err) | ||
|
|
||
| # Case 2: Custom message | ||
| err_custom = ReceiptStatusError(ResponseCode.FAIL_INVALID, tx_id_mock, receipt_mock, "Fatal receipt error") | ||
| assert str(err_custom) == "Fatal receipt error" |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.