Skip to content

Commit

Permalink
Merge pull request #135 from SparkPost/issue-134
Browse files Browse the repository at this point in the history
Tweaks to exception handling, refs #134.
  • Loading branch information
richleland authored Jan 13, 2017
2 parents cc577cc + f343c21 commit f3b27cc
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 8 deletions.
11 changes: 4 additions & 7 deletions sparkpost/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,14 @@ class SparkPostException(Exception):
class SparkPostAPIException(SparkPostException):
"Handle 4xx and 5xx errors from the SparkPost API"
def __init__(self, response, *args, **kwargs):
errors = None
try:
errors = response.json()['errors']
errors = [e['message'] +
' Code: ' + e.get('code', '') +
' Description: ' + e.get('description', '') +
'\n'
error_template = "{message} Code: {code} Description: {desc} \n"
errors = [error_template.format(message=e.get('message', ''),
code=e.get('code', 'none'),
desc=e.get('description', 'none'))
for e in errors]
except:
pass
if not errors:
errors = [response.text or ""]
self.status = response.status_code
self.response = response
Expand Down
14 changes: 14 additions & 0 deletions test/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,20 @@ def test_fail_nojson_request():
resource.request('GET', resource.uri)


@responses.activate
def test_fail_no_errors():
responses.add(
responses.GET,
fake_uri,
status=500,
content_type='application/json',
body='no errors'
)
resource = create_resource()
with pytest.raises(SparkPostAPIException):
resource.request('GET', resource.uri)


def test_fail_get():
resource = create_resource()
with pytest.raises(NotImplementedError):
Expand Down
2 changes: 1 addition & 1 deletion test/test_transmissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,7 @@ def test_fail_delete():
content_type='application/json',
body="""
{"errors": [{"message": "resource not found",
"description": "Resource not found:transmission id foobar""}]}
"description": "Resource not found:transmission id foobar"}]}
"""
)
with pytest.raises(SparkPostAPIException):
Expand Down

0 comments on commit f3b27cc

Please sign in to comment.