Skip to content

Commit 9937590

Browse files
committed
update http errors to provide useful information
1 parent aa5ac20 commit 9937590

File tree

3 files changed

+37
-13
lines changed

3 files changed

+37
-13
lines changed

docs/changelog.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ Master
2323
- :func:`~twitchio.Client.event_token_expired` will now be called correctly when response is ``401 Invalid OAuth token``
2424
- Fix reconnect loop when Twitch sends a RECONNECT via IRC websocket
2525
- Fix :func:`~twitchio.CustomReward.edit` so it now can enable the reward
26+
27+
- Other Changes
28+
- Updated the HTTPException to provide useful information when an error is raised.
2629

2730
- ext.eventsub
2831
- Added websocket support via eventsub.EventSubWSClient

twitchio/errors.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,11 +69,13 @@ class HTTPException(TwitchIOException):
6969
def __init__(
7070
self, message: str, *, reason: Optional[str] = None, status: Optional[int] = None, extra: Optional[Any] = None
7171
):
72-
self.message = message
72+
self.message = f"{status}: {message}: {reason}"
7373
self.reason = reason
7474
self.status = status
7575
self.extra = extra
7676

77+
super().__init__(self.message)
78+
7779

7880
class Unauthorized(HTTPException):
7981
pass

twitchio/http.py

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -190,42 +190,61 @@ async def _request(self, route, path, headers, utilize_bucket=True):
190190
await self.bucket.wait_reset()
191191
async with self.session.request(route.method, path, headers=headers, data=route.body) as resp:
192192
try:
193-
logger.debug(f"Received a response from a request with status {resp.status}: {await resp.json()}")
193+
message = await resp.text(encoding="utf-8")
194+
logger.debug(f"Received a response from a request with status {resp.status}: {message}")
194195
except Exception:
196+
message = None
195197
logger.debug(f"Received a response from a request with status {resp.status} and without body")
198+
196199
if 500 <= resp.status <= 504:
197200
reason = resp.reason
198201
await asyncio.sleep(2**attempt + 1)
199202
continue
203+
200204
if utilize_bucket:
201205
reset = resp.headers.get("Ratelimit-Reset")
202206
remaining = resp.headers.get("Ratelimit-Remaining")
203207

204208
self.bucket.update(reset=reset, remaining=remaining)
209+
205210
if 200 <= resp.status < 300:
206-
if resp.content_type == "application/json":
207-
return await resp.json(), False
208-
return await resp.text(encoding="utf-8"), True
209-
if resp.status == 401:
210-
message_json = await resp.json()
211+
if resp.content_type == "application/json" and message:
212+
return json.loads(message), False
213+
214+
return message, True
215+
216+
elif resp.status == 400:
217+
message_json = json.loads(message)
218+
raise errors.HTTPException(
219+
f"Failed to fulfill the request", reason=message_json.get("message", ""), status=resp.status
220+
)
221+
222+
elif resp.status == 401:
223+
message_json = json.loads(message)
211224
if "Invalid OAuth token" in message_json.get("message", ""):
212225
try:
213226
await self._generate_login()
227+
continue
214228
except:
215229
raise errors.Unauthorized(
216230
"Your oauth token is invalid, and a new one could not be generated"
217231
)
218-
print(resp.reason, message_json, resp)
219-
raise errors.Unauthorized("You're not authorized to use this route.")
220-
if resp.status == 429:
232+
233+
raise errors.Unauthorized(
234+
"You're not authorized to use this route.",
235+
reason=message_json.get("message", ""),
236+
status=resp.status,
237+
)
238+
239+
elif resp.status == 429:
221240
reason = "Ratelimit Reached"
222241

223242
if not utilize_bucket: # non Helix APIs don't have ratelimit headers
224243
await asyncio.sleep(3**attempt + 1)
244+
225245
continue
226-
raise errors.HTTPException(
227-
f"Failed to fulfil request ({resp.status}).", reason=resp.reason, status=resp.status
228-
)
246+
247+
raise errors.HTTPException(f"Failed to fulfill the request", reason=resp.reason, status=resp.status)
229248
raise errors.HTTPException("Failed to reach Twitch API", reason=reason, status=resp.status)
230249

231250
async def _generate_login(self):

0 commit comments

Comments
 (0)