-
Notifications
You must be signed in to change notification settings - Fork 4
feat: add error handling #47
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
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
5628895
add error handling to client.py using structure defined in errors.py
jake-valsamis 0c3fc23
Single Error class
zvikagart 1cc4cf0
Update src/codeocean/error.py
zvikagart 76ff231
fix
zvikagart 73917c4
return items in error message
jake-valsamis 25d47eb
fix
zvikagart 200e0f2
fix
zvikagart 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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,2 @@ | ||
| from codeocean.client import CodeOcean # noqa: F401 | ||
| from codeocean.error import Error # noqa: F401 |
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,41 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import requests | ||
|
|
||
|
|
||
| class Error(Exception): | ||
| """ | ||
| Represents an HTTP error with additional context extracted from the response. | ||
|
|
||
| Attributes: | ||
| http_err (requests.HTTPError): The HTTP error object. | ||
| status_code (int): The HTTP status code of the error response. | ||
| message (str): A message describing the error, extracted from the response body. | ||
| data (Any): If the response body is json, this attribute contains the json object; otherwise, it is None. | ||
|
|
||
| Args: | ||
| err (requests.HTTPError): The HTTP error object. | ||
| """ | ||
| def __init__(self, err: requests.HTTPError): | ||
| self.http_err = err | ||
| self.status_code = err.response.status_code | ||
| self.message = "An error occurred." | ||
| self.data = None | ||
|
|
||
| try: | ||
| self.data = err.response.json() | ||
| if isinstance(self.data, dict): | ||
| self.message = self.data.get("message", self.message) | ||
| except Exception: | ||
zvikagart marked this conversation as resolved.
Show resolved
Hide resolved
zvikagart marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| # response wasn't JSON – fall back to text | ||
| self.message = err.response.text | ||
|
|
||
| super().__init__(self.message) | ||
|
|
||
| def __str__(self) -> str: | ||
| msg = str(self.http_err) | ||
| msg += f"\n\nMessage: {self.message}" | ||
| if self.data: | ||
| msg += "\n\nData:\n" + json.dumps(self.data, indent=2) | ||
| return msg | ||
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,140 @@ | ||
| import unittest | ||
| from unittest.mock import Mock | ||
| import requests | ||
|
|
||
| from codeocean.error import Error | ||
|
|
||
|
|
||
| class TestError(unittest.TestCase): | ||
| """Test cases for the Error exception class.""" | ||
|
|
||
| def test_error_is_exception_subclass(self): | ||
| """Test that Error is a subclass of Exception.""" | ||
| self.assertTrue(issubclass(Error, Exception)) | ||
|
|
||
| def test_error_with_json_dict(self): | ||
| """Test Error creation with JSON dict response containing message.""" | ||
| # Create mock HTTPError and response | ||
| mock_response = Mock() | ||
| mock_response.status_code = 400 | ||
| mock_response.json.return_value = {"message": "Custom error message", "datasets": [{"id": "123", "name": "tv"}]} | ||
|
|
||
| mock_http_error = Mock(spec=requests.HTTPError) | ||
| mock_http_error.response = mock_response | ||
|
|
||
| # Create Error instance | ||
| error = Error(mock_http_error) | ||
|
|
||
| # Verify attributes | ||
| self.assertEqual(error.status_code, 400) | ||
| self.assertEqual(error.message, "Custom error message") | ||
| self.assertEqual(error.data, {"message": "Custom error message", "datasets": [{"id": "123", "name": "tv"}]}) | ||
|
|
||
| def test_error_with_json_dict_no_message(self): | ||
| """Test Error creation with JSON dict response without message field.""" | ||
| # Create mock HTTPError and response | ||
| mock_response = Mock() | ||
| mock_response.status_code = 500 | ||
| mock_response.json.return_value = {"error": "some other field"} | ||
|
|
||
| mock_http_error = Mock(spec=requests.HTTPError) | ||
| mock_http_error.response = mock_response | ||
|
|
||
| # Create Error instance | ||
| error = Error(mock_http_error) | ||
|
|
||
| # Verify attributes | ||
| self.assertEqual(error.status_code, 500) | ||
| self.assertEqual(error.message, "An error occurred.") | ||
| self.assertEqual(error.data, {"error": "some other field"}) | ||
|
|
||
| def test_error_with_json_list(self): | ||
| """Test Error creation with JSON list response.""" | ||
| # Create mock HTTPError and response | ||
| mock_response = Mock() | ||
| mock_response.status_code = 403 | ||
| mock_response.json.return_value = [{"field": "error1"}, {"field": "error2"}] | ||
|
|
||
| mock_http_error = Mock(spec=requests.HTTPError) | ||
| mock_http_error.response = mock_response | ||
|
|
||
| # Create Error instance | ||
| error = Error(mock_http_error) | ||
|
|
||
| # Verify attributes | ||
| self.assertEqual(error.status_code, 403) | ||
| self.assertEqual(error.message, "An error occurred.") | ||
| self.assertEqual(error.data, [{"field": "error1"}, {"field": "error2"}]) | ||
|
|
||
| def test_error_with_non_json_response(self): | ||
| """Test Error creation when response is not JSON.""" | ||
| # Create mock HTTPError and response | ||
| mock_response = Mock() | ||
| mock_response.status_code = 404 | ||
| mock_response.json.side_effect = Exception("Not JSON") | ||
| mock_response.text = "Page not found" | ||
|
|
||
| mock_http_error = Mock(spec=requests.HTTPError) | ||
| mock_http_error.response = mock_response | ||
|
|
||
| # Create Error instance | ||
| error = Error(mock_http_error) | ||
|
|
||
| # Verify attributes | ||
| self.assertEqual(error.status_code, 404) | ||
| self.assertEqual(error.message, "Page not found") | ||
| self.assertIsNone(error.data) | ||
|
|
||
| def test_error_str_method_with_data(self): | ||
| """Test Error __str__ method when data is present.""" | ||
| # Create mock HTTPError and response | ||
| mock_response = Mock() | ||
| mock_response.status_code = 400 | ||
| mock_response.json.return_value = {"message": "Validation failed", "errors": ["field1", "field2"]} | ||
|
|
||
| mock_http_error = Mock(spec=requests.HTTPError) | ||
| mock_http_error.response = mock_response | ||
| mock_http_error.__str__ = Mock(return_value="400 Client Error: Bad Request for url: http://example.com") | ||
|
|
||
| # Create Error instance | ||
| error = Error(mock_http_error) | ||
|
|
||
| # Test __str__ method | ||
| error_str = str(error) | ||
|
|
||
| # Verify the string contains expected components | ||
| self.assertEqual(error_str, """400 Client Error: Bad Request for url: http://example.com | ||
|
|
||
| Message: Validation failed | ||
|
|
||
| Data: | ||
| { | ||
| "message": "Validation failed", | ||
| "errors": [ | ||
| "field1", | ||
| "field2" | ||
| ] | ||
| }""") | ||
|
|
||
| def test_error_str_method_without_data(self): | ||
| """Test Error __str__ method when data is None.""" | ||
| # Create mock HTTPError and response | ||
| mock_response = Mock() | ||
| mock_response.status_code = 404 | ||
| mock_response.json.side_effect = Exception("Not JSON") | ||
| mock_response.text = "Page not found" | ||
|
|
||
| mock_http_error = Mock(spec=requests.HTTPError) | ||
| mock_http_error.response = mock_response | ||
| mock_http_error.__str__ = Mock(return_value="404 Client Error: Not Found for url: http://example.com") | ||
|
|
||
| # Create Error instance | ||
| error = Error(mock_http_error) | ||
|
|
||
| # Test __str__ method | ||
| error_str = str(error) | ||
|
|
||
| # Verify the string contains expected components | ||
| self.assertEqual(error_str, """404 Client Error: Not Found for url: http://example.com | ||
|
|
||
| Message: Page not found""") |
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.