Skip to content
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
22 changes: 14 additions & 8 deletions stripe/_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,20 @@ def __init__(
super(StripeError, self).__init__(message)

body: Optional[str] = None
if http_body and hasattr(http_body, "decode"):
try:
body = cast(bytes, http_body).decode("utf-8")
except BaseException:
body = (
"<Could not decode body as utf-8. "
"Please report to support@stripe.com>"
)
if http_body:
# http_body can sometimes be a memoryview which must be cast
# to a "bytes" before calling decode, so we check for the
# decode attribute and then cast
if hasattr(http_body, "decode"):
try:
body = cast(bytes, http_body).decode("utf-8")
except BaseException:
body = (
"<Could not decode body as utf-8. "
"Please report to support@stripe.com>"
)
elif isinstance(http_body, str):
body = http_body

self._message = message
self.http_body = body
Expand Down
17 changes: 17 additions & 0 deletions tests/test_error.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-


import json
from stripe import error


Expand Down Expand Up @@ -28,6 +29,22 @@ def test_repr(self):
"request_id='123')"
)

def test_error_string_body(self):
http_body = '{"error": {"code": "some_error"}}'
err = error.StripeError(
"message", http_body=http_body, json_body=json.loads(http_body)
)
assert err.http_body is not None
assert err.http_body == json.dumps(err.json_body)

def test_error_bytes_body(self):
http_body = '{"error": {"code": "some_error"}}'.encode("utf-8")
err = error.StripeError(
"message", http_body=http_body, json_body=json.loads(http_body)
)
assert err.http_body is not None
assert err.http_body == json.dumps(err.json_body)

def test_error_object(self):
err = error.StripeError(
"message", json_body={"error": {"code": "some_error"}}
Expand Down
Loading