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

fix: handle_errors should handle non-JSON error responses #19

Merged
merged 2 commits into from
Feb 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 12 additions & 8 deletions src/posit/connect/hooks.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
from http.client import responses
from requests import Response
from requests import JSONDecodeError, Response

from .errors import ClientError


def handle_errors(response: Response, *args, **kwargs) -> Response:
if response.status_code >= 400 and response.status_code < 500:
data = response.json()
error_code = data["code"]
message = data["error"]
http_status = response.status_code
http_status_message = responses[http_status]
raise ClientError(error_code, message, http_status, http_status_message)
if response.status_code >= 400:
try:
data = response.json()
error_code = data["code"]
message = data["error"]
http_status = response.status_code
http_status_message = responses[http_status]
raise ClientError(error_code, message, http_status, http_status_message)
except JSONDecodeError:
# No JSON error message from Connect, so just raise
response.raise_for_status()
return response
15 changes: 12 additions & 3 deletions src/posit/connect/hooks_test.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import pytest

from requests import HTTPError, JSONDecodeError
from unittest.mock import Mock

from .errors import ClientError
from .hooks import handle_errors


Expand All @@ -14,7 +16,14 @@ def test(self):
def test_client_error(self):
response = Mock()
response.status_code = 400
response.json = Mock()
response.json.return_value = {"code": 0, "error": "foobar"}
with pytest.raises(Exception):
response.json = Mock(return_value={"code": 0, "error": "foobar"})
with pytest.raises(ClientError):
handle_errors(response)

def test_client_error_not_json(self):
response = Mock()
response.status_code = 404
response.json = Mock(side_effect=JSONDecodeError("Not Found", "", 0))
response.raise_for_status = Mock(side_effect=HTTPError())
with pytest.raises(HTTPError):
handle_errors(response)
Loading