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 StripeError http_body #1435

Merged
merged 2 commits into from
Dec 16, 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
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 [email protected]>"
)
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 [email protected]>"
)
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